列表推导式的第一个表达式可以是任何表达式,包括另外一个列表推导式。
考虑下面的3×4矩阵的示例,其被实现为长度为4的3个列表的列表:
list = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
#下面的列表推导式将转置行和列:
new_list = [[n[i] for n in list] for i in range(4)]
print(new_list)
#输出结果:
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
上面的例子等效于:
list = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
li = []
for i in range(4):
li.append([n[i] for n in list])
print(li)
#输出结果:
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
内建函数复杂的流程句,zip()函数这个更容易实现:
list = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
list(zip(*list))
输出:
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
原文地址:https://blog.51cto.com/14113984/2431206
时间: 2024-10-09 09:13:28