List 如何垂直遍历列表?

List 如何垂直遍历列表?,list,loops,for-loop,python-3.x,collections,List,Loops,For Loop,Python 3.x,Collections,我要处理多个列表。我要做的是为垂直列中的每个列表(在本例中为索引1、2和3)获取一个特定的索引。并将这些垂直数字添加到空列表中 line1=[1,2,3,4,5,5,6] line2=[3,5,7,8,9,6,4] line3=[5,6,3,7,8,3,7] vlist1=[] vlist2=[] vlist3=[] 预期产量 Vlist1=[1,3,5] Vlist2=[2,5,6] Vlist3=[3,7,3] 使用pythons函数,相应地索引 >>> line1

我要处理多个列表。我要做的是为垂直列中的每个列表(在本例中为索引1、2和3)获取一个特定的索引。并将这些垂直数字添加到空列表中

line1=[1,2,3,4,5,5,6]
line2=[3,5,7,8,9,6,4]
line3=[5,6,3,7,8,3,7]

vlist1=[]
vlist2=[]
vlist3=[]
预期产量

Vlist1=[1,3,5] 
Vlist2=[2,5,6]
Vlist3=[3,7,3]
使用pythons函数,相应地索引

>>> line1=[1,2,3,4,5,5,6]
>>> line2=[3,5,7,8,9,6,4]
>>> line3=[5,6,3,7,8,3,7]
>>> zip(line1,line2,line3)
[(1, 3, 5), (2, 5, 6), (3, 7, 3), (4, 8, 7), (5, 9, 8), (5, 6, 3), (6, 4, 7)]

使用带有数字的变量通常是一种设计错误。相反,您可能应该有一个嵌套的数据结构。如果使用
line1
line2
line3
列表执行此操作,则会得到一个嵌套列表:

lines = [[1,2,3,4,5,5,6],
         [3,5,7,8,9,6,4],
         [5,6,3,7,8,3,7]]
然后,您可以使用
zip
“转置”此列表:

vlist = list(zip(*lines)) # note the list call is not needed in Python 2
现在,您可以通过索引或切片到转置列表中来访问内部列表(现在实际上是元组)

first_three_vlists = vlist[:3]

在python 3
zip
中,返回一个生成器对象,您需要将其视为一个:

from itertools import islice

vlist1,vlist2,vlist3 = islice(zip(line1,line2,line3),3)
但你真的应该。使用列表数据结构,如果需要转换,只需执行以下操作:

list(zip(*nested_list))
Out[13]: [(1, 3, 5), (2, 5, 6), (3, 7, 3), (4, 8, 7), (5, 9, 8), (5, 6, 3), (6, 4, 7)]

将输入列表放入列表中。然后,要创建第i个列表,请执行以下操作:

vlist[i] = [];
for l in list_of_lists:
    vlist[i].append(l[i])