The first list of expressions derived formulas can be any expression, further comprising a list of comprehension.
Consider the example below 3 × 4 matrix, which is implemented as a list of length 3 List 4:
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]]
The above example is equivalent to:
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]]
Built complex processes sentence function, zip () function is easier to achieve this:
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)]