number of values in a list greater than a certain number
You could do something like this:
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3
It might initially seem strange to add True
to True
this way, but I don't think it's unpythonic; after all, bool
is a subclass of int
in all versions since 2.3:
>>> issubclass(bool, int)
True
You can create a smaller intermediate result like this:
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> len([1 for i in j if i > 5])
3
if you are otherwise using numpy, you can save a few strokes, but i dont think it gets much faster/compact than senderle's answer.
import numpy as np
j = np.array(j)
sum(j > i)
A (somewhat) different way:
reduce(lambda acc, x: acc + (1 if x > 5 else 0), j, 0)