开发者

Use lambda expression to count the elements that I'm interested in Python

开发者 https://www.devze.com 2023-04-07 04:30 出处:网络
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 thi开发者_JAVA百科s code which returns 0

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 thi开发者_JAVA百科s 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)


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 )


from functools import reduce

x = [1,2,3]
reduce(lambda a,i: a+1 if (i>2) else a, x, 0)

This will not create a new list. a is the accumulator variable, i is the item from the list, and the 0 at the end is the initial value of the accumulator.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号