python中类怎么理解_Python中的列表理解
python中類怎么理解
In order to create a list, a most obvious and remembered solution is to use a for-loop.
為了創建列表,最明顯和記住的解決方案是使用for循環。
Example:
例:
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information.>>> flights = {'09:35':'Long Beach', '10:00':'los-angeles', '11:00':'san jose'} >>> flight_time_list = [] >>> for key in flights.keys(): ... flight_time_list.append(key) ... >>> print(flight_time_list) ['09:35', '10:00', '11:00'] >>>Python's built-in comprehension feature that lets us reduce the number of lines in list creation to a single line.
Python的內置理解功能使我們可以將列表創建中的行數減少為一行。
Example:
例:
-bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information.>>> flights = {'09:35':'Long Beach', '10:00':'los-angeles', '11:00':'san jose'} >>> flight_time_list = [ key for key in flights.keys()] >>> print(flight_time_list) ['09:35', '10:00', '11:00'] >>>列表理解的語法 (Syntax for list comprehension)
The list comprehension starts with a [ and ], to ensure that the result is a list.
列表理解以[和]開頭,以確保結果為列表。
[expression for item in list]The comprehension can also utilize the if condition.
理解也可以利用if條件 。
Example: Grouping the common items to a list
示例:將常見項目分組到列表中
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information.>>> grade_k = ['maddy', 'sriansh', 'owen', 'molly'] >>> grade_first = ['molly', 'owen', 'ricky', 'sid'] >>> common_names = [a for a in grade_k for b in grade_first if a==b] >>> print(common_names) ['owen', 'molly'] >>>使用理解的優勢 (Advantages of using Comprehension)
Comprehensions requires less code. Python interpreter is optimized to run comprehensions as quickly as possible.
理解需要更少的代碼。 Python解釋器經過優化,可以盡快運行理解。
Comprehensions execute faster than for loop.
理解的執行速度比for循環快。
Comprehensions can be used in places where for loop cannot be used. All the comprehensions appear to the right of the assignment operator, which is something for loop cannot do.
可以在無法使用for循環的地方使用理解 。 所有的理解都出現在賦值運算符的右邊,這是for循環無法做到的。
翻譯自: https://www.includehelp.com/python/list-comprehension.aspx
python中類怎么理解
總結
以上是生活随笔為你收集整理的python中类怎么理解_Python中的列表理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c ++查找字符串_C ++结构| 查找
- 下一篇: python线程任务run_Python