遍历列表列表,根据索引将每个项目附加到新列表中



我想要一个列表列表,每个列表包含6个项目,并根据索引位置将每个项目附加到6个新列表中。

以下是我迄今为止所尝试的:

pos1 = []
pos2 = []
pos3 = []
pos4 = []
pos5 = []
pos6 = []
numbers = [[2,3,4,5,6,7][12,34,65,34,76,78][1,2,3,4,5,6][21,34,5,87,45,76][76,45,34,23,5,24]]
index_count = 0
while True:
index_count < 6
print(index_count)
for l in numbers:
for item in l:
time.sleep(1)
print(pos1)
if index_count == 0:
pos1.append(item)
index_count = index_count + 1
elif index_count == 1:
pos2.append(item)
index_count = index_count + 1
elif index_count == 2:
pos3.append(item)
index_count = index_count + 1
elif index_count == 3:
pos4.append(item)
index_count = index_count + 1
elif index_count == 4:
pos5.append(item)
index_count = index_count + 1
elif index_count == 5:
pos6.append(item)
index_count = index_count + 1
else:
break
print('working...')

我正试图得到这样的数据列表:

pos1 = [2,12,1,21,76]
pos2 = [3,34,2,34,45]
pos3 = [4,65,3,5,34]
pos4 = [5,34,4,87,23]
pos5 = [6,76,5,45,5]
pos6 = [7,78,6,76,24]

zip()*:一起使用

numbers = [[2,3,4,5,6,7], [12,34,65,34,76,78], [1,2,3,4,5,6], [21,34,5,87,45,76], [76,45,34,23,5,24]]
pos1,pos2,pos3,pos4,pos5,pos6 = map(list, zip(*numbers))
print(pos1)
print(pos2)
print(pos3)
print(pos4)
print(pos5)
print(pos6)

打印:

[2, 12, 1, 21, 76]
[3, 34, 2, 34, 45]
[4, 65, 3, 5, 34]
[5, 34, 4, 87, 23]
[6, 76, 5, 45, 5]
[7, 78, 6, 76, 24]

最新更新