Python:如何在不知道子列表数量的情况下迭代每个子列表的第一个元素?

时间:2013-05-29 22:05:54

标签: python

我有一个包含多个子列表的列表。

l = [[a,b,c],[3,5,0],[3,1,0],...]  # I do not know how many sublists there are beforehand. 

我如何迭代每个子列表的第一项?

e.g. a,3,3 then b,5,1 ...

我想做点什么:

for x,y,z... in zip(l[1],l[2],l[3]...) # "..." representing other sublists 
    do something with x,y,z... if condition...

当然这不起作用,因为我不知道预先存在多少个子列表。

最终,我想过滤现有的子列表,如果在同一索引处,所有数值都等于零。例如:c,0,0将被删除(因为所有数字都是零)。但是,a,3,3和b,5,1仍然存在。最后,我需要3个新的过滤子列表来包含:

lnew = [[a,b],[3,5],[3,1]] 

3 个答案:

答案 0 :(得分:5)

来自docs

  

zip()*运算符一起用于解压缩列表

>>> lis = [['a','b','c'],[3,5,0],[3,1,0]] 
>>> for x,y,z in zip(*lis):
    print x,y,z
...     
a 3 3
b 5 1
c 0 0
  

我想过滤现有的子列表,如果在同一个索引处,全部   数值等于零

>>> zipp = [x for x in zip(*lis) if any(y != 0 for y in x \
                                             if isinstance (y,(int,float)) ) ]
>>> zip(*zipp)
[('a', 'b'), (3, 5), (3, 1)]

答案 1 :(得分:2)

类似的东西:

from numbers import Number
lis = [['a','b','c'],[3,5,0],[3,1,0]] 
print [list(el) for el in zip(*[el for el in zip(*lis) 
       if any(i for i in el if isinstance(i, Number))])]
# [['a', 'b'], [3, 5], [3, 1]]              

答案 2 :(得分:2)

呃,这里的答案似乎很好,但我会提供另一种选择:

l = [['a', 'b', 'c'], [3, 5, 0], [3, 1, 0]]
i = 0
while True:
    try:
        do_whatever(l[i][0])
        i += 1

    except IndexError:
        break

我意识到它并不像其他解决方案那样优雅,但很高兴有各种各样的选择!

如果您在迭代时仍然添加到列表中,这仍然有效!