Python列表。查找所有元素不为零的最大行

时间:2012-11-10 01:56:52

标签: python list numpy max

我有一个python列表,看起来有点像这样:

[[0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,90,1,9999,0,0,0,0,0,0,0,00,0],
[0,0,0,0,0,0,0,0,0,0,0,0,00,0],[0,0,90,1,9999,1,2,0,0,9999,0,0,00,0].....till about 30 rows]

我需要从此列表中找到最大行,其中包含9999或者换句话说,其中没有所有元素为零。请帮我解决一下这个。谢谢!

我试过了:

print max((numpy.where(v1==9999)[0])) 

但这只是给了我一些奇怪的错误,比如'int' object not iterablenumpy.where does not accept keywords n等等!!

3 个答案:

答案 0 :(得分:2)

你想要:

idx,row = max(enumerate(lst),key=lambda r: ( sum(r[1])==0, r[0] ) )

其中lst是您的列表。

或者你想要:

next(x for x in reversed(lst) if sum(x) != 0)

答案 1 :(得分:0)

    python 3.2

    #   if you want to find how many rows in your list has 9999
    v=[[0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,90,1,9999,0,0,0,0,0,0,0,00,0]]

    len([i for i in v if 9999 in i])




 #   if any element in your rows is 9999 then all the elements of that row 
 # cannot be 0. then if you want to know how many rows have all the elements 0.


     len([i for i in v if sum(i)==0])

答案 2 :(得分:0)

这将返回具有非“全零”行的索引:

nonzerorows = [i for i,j in enumerate(a) if any(j)]

此类行的最高索引:

maxnonzerorows = max([i for i,j in enumerate(a) if any(j)])