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

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

最佳答案

来自 docs :

zip() in conjunction with the * operator can be used to unzip a list

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

I want to filter the existing sublists if at the same index, all numerical values are equal to zero

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

关于Python:如何在不知道子列表数量的情况下迭代每个子列表的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16824695/

相关文章:

python 列表回溯的排列

python - pb 在 python optparse 模块中带有回调

python - 如何让 conda 命令匹配 Vscode 集成终端和普通终端中的行为?

python - 为什么出现此错误(程序因使用13 cpu秒而关闭)

python / Pandas : Use lookup DataFrame + function to replace specific/null values in DataFrame

python - 将十六进制字符串拆分为 Python 中的列表 - 如何?

python - 如何去除模板匹配 (opencv) y 轴的变化

python - JSON 中双引号前添加反斜杠

python - Django:何时自定义保存与使用保存后信号

python - 如何生成我用 jose.jwt.decode 解码的 RS256 签名 token