Python中的列表推导是一种从其他列表创建列表的方式,类似于数学中的集合推导。
举个简单例子:
lists = [x * x for x in range(10)]
其结果如下:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
它的计算结果和我们使用以下代码的计算结果相同:
for num in range(10): list2.append(num * num)
此外我们还可以通过推导实现更多复杂的功能,示例如下:
list1 = ['a', 'b', 'c', 'd'] list2 = ['1', '2', '3', '4'] listResult = [l1 + "+" + l2 for l1 in list1 for l2 in list2 if len(l1) == len(l2)]
其结果如下:
['a+1', 'a+2', 'a+3', 'a+4', 'b+1', 'b+2', 'b+3', 'b+4', 'c+1', 'c+2', 'c+3', 'c+4', 'd+1', 'd+2', 'd+3', 'd+4']
该推导和下列代码效果相同:
listResult2 = [] for l1 in list1: for l2 in list2: if len(l1) == len(l2): listResult2.append(l1 + "+" + l2)