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)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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)