【问题标题】:Python: how do i iterate over the first element of each sublist without knowing the number of sublists?Python:如何在不知道子列表数量的情况下迭代每个子列表的第一个元素?
【发布时间】:2013-05-30 06:37:46
【问题描述】:

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

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]] 

【问题讨论】:

    标签: python


    【解决方案1】:

    来自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)]
    

    【讨论】:

    • 您需要使用元组而不是 x, y, z,因为 OP 不知道 lis 中有多少元素。
    • 我认为 Ashwini 在 x 更改为 x,y,z 之前就拥有它。
    【解决方案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
    

    我意识到它不像其他解决方案那样优雅,但有多种选择真是太好了!

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

    【讨论】:

      【解决方案3】:

      类似:

      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]]              
      

      【讨论】:

        猜你喜欢
        • 2017-05-24
        • 1970-01-01
        • 2023-03-30
        • 2021-06-11
        • 1970-01-01
        • 1970-01-01
        • 2017-10-07
        • 1970-01-01
        • 2018-02-14
        相关资源
        最近更新 更多