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中类怎么理解