列表推导式
列表推导式提供了从序列创建列表的简单途径。通常应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。
每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。如果希望表达式推导出一个元组,就必须使用括号。
这里我们将列表中每个数值乘三,获得一个新的列表:
]
*x for x in vec]
]
*x for x in vec]
]
现在我们玩一点小花样:
] for x in vec]
]]
]]
这里我们对序列里每一个元素逐个调用某方法:
实例
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
我们可以用 if 子句作为过滤器:
*x ]
]
*x ]
[]
]
*x ]
[]
以下是一些关于循环和其它技巧的演示:
]
]
>>> [x*y for x in vec1 for y in vec2]
]
>>> [x+y for x in vec1 for y in vec2]
]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
]
]
>>> [x*y for x in vec1 for y in vec2]
]
>>> [x+y for x in vec1 for y in vec2]
]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
]
列表推导式可以使用复杂表达式或嵌套函数:
/)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
['3.1', '3.14', '3.142', '3.1416', '3.14159']
嵌套列表解析
Python的列表还可以嵌套。
以下实例展示了3X4的矩阵列表:
>>> matrix = [
... ],
... ],
... ],
... ]
... ],
... ],
... ],
... ]
以下实例将3X4的矩阵列表转换为4X3列表:
)]
]]
]]
以下实例也可以使用以下方法来实现:
>>> transposed = []
):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
]]
):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
]]
另外一种实现方法:
>>> transposed = []
):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
]
):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
]