这个问题很简单,但是我没有得到想要的输出。
alist = [[0., 0., 0], [1 , 2, 3 ], [4, 5, 6 ],[7, 8, 9], [10, 11, 12], [13, 14, 15]]
a = []
for i in alist:
for j in i:
a.append(j[0:3])
print(a)
期望输出:
a = [ [0, 1, 4, 7, 10, 13 ], [0, 2, 5, 8, 11, 14 ], [0, 3, 6, 9, 12, 15 ] ]
您可以像使用zip(*alist)
一样使用zip
并得到您想要的,但是如果您想要纠正您的代码。你需要enumerate
。
>>> list(map(list, zip(*alist)))
[[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]
代码:
a = [[],[],[]] # <- change this
for i in alist:
for idx, j in enumerate(i): # <- change this
a[idx].append(j) # <- change this
print(a)
输出:
[[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]
你可以使用列表理解结合zip和拆包:
>>> [list(x) for x in zip(*alist)]
#output:
# [[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]