簡體   English   中英

Python:如何在不知道子列表數目的情況下遍歷每個子列表的第一個元素?

[英]Python: how do i iterate over the first element of each sublist without knowing the number of sublists?

我有一個帶有多個子列表的列表。

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

文檔

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

就像是:

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

嗯,這里的答案似乎不錯,但我會提供另一種選擇:

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

我意識到它不像其他解決方案那樣優雅,但是很高興有多種選擇!

如果在迭代過程中仍要添加到列表中,這仍然有效!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM