[英]Python List. Finding the maximum row with all elements not zero
I have a python list which looks a little like this: 我有一个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]
I need to find the maximum row from this list which has a 9999 or in other words, which does not have all elements zero. 我需要找到这个列表中有一个9999的最大行,换句话说,它没有所有元素为零。 Please help me with this. 请帮我解决一下这个。 Thanks!! 谢谢!!
I tried: 我试过了:
print max((numpy.where(v1==9999)[0]))
but this just gave me some weird errors like 'int' object not iterable
or numpy.where does not accept keywords n
and so on!! 但这只是给了我一些奇怪的错误,如'int' object not iterable
或numpy.where does not accept keywords n
等等!
Do you want: 你想要:
idx,row = max(enumerate(lst),key=lambda r: ( sum(r[1])==0, r[0] ) )
where lst
is your list. 其中lst
是你的清单。
Or do you want: 或者你想要:
next(x for x in reversed(lst) if sum(x) != 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])
This will return the indices that have non-"all-zero" rows: 这将返回具有非“全零”行的索引:
nonzerorows = [i for i,j in enumerate(a) if any(j)]
And the highest index of such rows: 并且这类行的最高索引:
maxnonzerorows = max([i for i,j in enumerate(a) if any(j)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.