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)

  1. Comprehensions requires less code. Python interpreter is optimized to run comprehensions as quickly as possible.

    理解需要更少的代码。 Python解释器经过优化,可以尽快运行理解。

  2. Comprehensions execute faster than for loop.

    理解的执行速度比for循环快。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值