列表推导式

List Comprehensions 列表推导式
List comprehensions provide a concise way to create lists without resorting to use of map(),
filter() and/or lambda. The resulting list definition tends often to be clearer than lists
built using those constructs. Each list comprehension consists of an expression followed by
a for clause, then zero or more for or if clauses. The result will be a list resulting from
evaluating the expression in the context of the for and if clauses which follow it. If the
expression would evaluate to a tuple, it must be parenthesized. :
列表推导式提供了一个创建链表的简单途径,无需使用 map() , filter() 以及 lambda 。以定义方式得
到列表通常要比使用构造函数创建这些列表更清晰。每一个列表推导式包括 在一个 for 语句之后的表达
式,零或多个 for 或 if 语句。返回值是由 for 或 if 子句之后的表达式得到的元素组成的列表。如果
想要得到一个元组,必须要加 上括号。

freshfruit = [’ banana’, ’ loganberry ‘, ‘passion fruit ‘]
[weapon.strip() for weapon in freshfruit]
[‘banana’, ‘loganberry’, ‘passion fruit’]
vec = [2, 4, 6]
[3*x for x in vec]
[6, 12, 18]
[3*x for x in vec if x > 3]
[12, 18]
[3*x for x in vec if x < 2]
[]
[[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
[x, x**2 for x in vec] # error - parens required for tuples
File “”, line 1, in ?
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
[(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
[x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
[vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
List comprehensions are much more flexible than map() and can be applied to complex expressions
and nested functions:
列表推导式比 map() 更复杂,可使用复杂的表达式和嵌套函数这里写代码片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值