Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

lambda

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)
like image 620
prosseek Avatar asked Sep 26 '11 00:09

prosseek


People also ask

How do you use lambda function in python?

We can use the apply() function to apply the lambda function to both rows and columns of a dataframe. If the axis argument in the apply() function is 0, then the lambda function gets applied to each column, and if 1, then the function gets applied to each row.

Can lambda expressions contain statements python?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.

What is a lambda function in python Please explain your answer with an example?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Can lambda return 2 values python?

That's not more than one return, it's not even a single return with multiple values. It's one return with one value (which happens to be a tuple).


3 Answers

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)

like image 52
John Machin Avatar answered Oct 05 '22 05:10

John Machin


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 )
like image 42
donkopotamus Avatar answered Oct 05 '22 03:10

donkopotamus


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.

like image 20
Brent Avatar answered Oct 05 '22 03:10

Brent