Can I use lambda expression to count the elements that I'm interested? For example, when I need to count the elements in a list that is more than two, I tried this code which returns 0.
x = [1,2,3]
x.count(lambda x: x > 2)
Note: "more than" is > ... => is not a valid operator.
Try sum(y > 2 for y in x)
Or, as suggested by @Jochen, to guard against non-conventional nth-party classes, use this:
sum(1 for y in x if y > 2)
lambda is not necessary.sum(1 for y in x if y > 2)y > 2 should not run amok. I don't see the point of float(y). Yes, some badass class could define comparison operators that return neither True nor 1 for truthy results -- in which case, the suggestion of @Jochen [Thanks!] avoids the explicit bool()sum(1 for y in x if y > 2) is IMHO the best and most Pythonic answer.You can try any of the following
len([y for y in x if y > 2])
or
len(filter(lambda y: y > 2, x))
or the nicer
sum( y > 2 for y in x )
filter returns a generator in Python 3.x meaning that suggested method is no longer applicable.len(list(filter(lambda y: y > 2, x)))
lambdas?