说我有几个列表
A = [1,2,3]
B = [4,5,6]
C = [7,8,9]
如何创建新列表以使其包含匹配的索引,如:
D = [1,4,7]
E = [2,5,8]
F = [3,6,9]
原始列表将始终包含相同数量的元素,我需要它适用于任意数量的元素和任意数量的列表,而不仅仅是三个。我想我需要在一个范围内循环,但我不知道该怎么做。
如果我理解正确,您可能正在寻找zip():
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [7, 8, 9]
>>> zipped = zip(a, b, c)
>>> zipped
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
如果您有一个要压缩的列表列表,而不是多个列表,则可以*
用于解压缩子列表,如下所示:
>>> myListOfLists = [[1,2,3],[4,5,6],[7,8,9]]
>>> zipped = zip(*myListOfLists)
>>> zipped
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]