迭代列表列表,根据索引将每个项目附加到新列表中[重复]

问题描述 投票:0回答:1

我想获取一个列表列表,每个列表包含 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]
python python-3.x for-loop indexing list-comprehension
1个回答
2
投票

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]
© www.soinside.com 2019 - 2024. All rights reserved.