I have a list
J. I want to identify number of non-zero elements and divide by 12 and then multiply by 100. But I get an error. I present the expected output.
J=[[1, 4, 0, 0, 0, 9, 0]] Percent_Unvisited=(len(J!=0)/12)*100 print(Percent_Unvisited)
The error is
in <module> Percent_Unvisited=(len(J!=0)/12)*100 TypeError: object of type 'bool' has no len()
The expected output is
You can use a generator expression with
sum to count the number of elements that are non-zero. This works because
False are equivalent to
0, respectively, when used in arithmetic.
Percent_Unvisited = sum(x != 0 for x in J) / 12 * 100