I have list or/and tuple:
MyVar = [0,0,0,0,1,0,0,0,0]
And I want to count elements in this which are different from 0
.
How to do that?
I have list or/and tuple:
MyVar = [0,0,0,0,1,0,0,0,0]
And I want to count elements in this which are different from 0
.
How to do that?
Get the length of the sublist of all elements that are not 0
MyVar = [0,0,0,0,1,0,0,0,0]
len([x for x in MyVar if x != 0])
>> 1
You could try:
>>> len(filter(lambda x: x != 0, MyVar))
1
The following should work:
>>> MyVar = [0,0,0,0,1,0,0,0,0]
>>> sum(map(bool, MyVar))
1
It will convert the list to a list of booleans, with value True
iff an element is nonzero. Then it'll sum all elements by implicitly considering True
having value 1 and False
having value 0.
Try with filter()
:
>>> my_var = [0, 0, 0, 0, 1, 0, 0, 0, 0]
>>> result = filter(lambda x: x > 0, my_var)
[1]
>>> print(len(result))
1
You could do a sum
over a conditional generator expression which doesn't require any intermediate lists or unnecessary arithmetic operations:
>>> sum(1 for element in MyVar if element != 0)
1
or as pointed out by @Jean-François Fabre:
>>> sum(1 for element in MyVar if element)
1
In case the MyVar
only contains numbers this counts the number of not-zero values.
Not nearly as efficient as any of the answers above, but simple and straight forward nonetheless
myVar = [0,0,0,0,1,0,0,0,0]
count = 0
for var in myVar:
if var != 0:
count += 1
With reduce from functools:
from functools import reduce
reduce((lambda x, y: x + (y>0)), MyVar, 0)
f = sum([1 for x in MyVar if x!= 0])
One line :)