数据结构
[]返回list,()返回生成器
列表推导式
列表推导式提供了从序列创建列表的简单途径。
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]
#输出每个值 并将每个值2次方
[[x, x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
用 if 子句作为过滤器:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
(1) 一般形式
mylist=[x+1 for x in range(1,100,2)]
print(mylist)
(2) 一般形式+判断
mylist=[x+1 for x in range(1,100,2) if x<50]
(3) 生成列表嵌套列表
mylist=[[x,x+1,x*x] for x in range(10) if x>5]
(4) 嵌套循环
mylist=[x+y for x in range(10) for y in range(10)]
mylist=[[x,y] for x in range(10) for y in range(10)]
拆分
for x in range(3):
for y in range(10):
print([x,y])
嵌套列表解析
Python的列表还可以嵌套。
以下实例展示了3X4的矩阵列表:
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
以下实例将3X4的矩阵列表转换为4X3列表:
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
另外一种实现方法:
>>> transposed = []
>>> for i in range(4):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
字典推导式
可能你见过列表推导时,却没有见过字典推导式,在2.7中才加入的:
1 | d = {key: value for (key, value) in iterable} |
---|---|
d = {key: value for key, value in [('a','a'),('b','b')]} |
网友评论