我有一个包含多个子列表的列表。
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/