Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract values from a list based on a condition

Tags:

python-2.7

I am trying to get a sample from a list based on a condition. It should be easy to do but I am unable to do it as following:

a = [2,4,5,9,1,6,4]
b = 6
c = [x for x in a if a < b]

I basically need a new list which should contain values less than 6. Any suggestions?

like image 843
Ibe Avatar asked Aug 25 '13 05:08

Ibe


2 Answers

Or, the other way:

>>> a = [2,4,5,9,1,6,4]
>>> b = 6
>>> c = filter(lambda x: x < b, a)
>>> c
[2, 4, 5, 1, 4]

You almost had it as Ignacio pointed out:

>>> c = [x for x in a if x < b]
>>> c
[2, 4, 5, 1, 4]

The list comprehension is a longer way of writing this loop:

>>> c = []
>>> for x in a:
...     if x < b:
...         c.append(x)
...
>>> c
[2, 4, 5, 1, 4]
like image 152
Burhan Khalid Avatar answered Nov 13 '22 09:11

Burhan Khalid


You missed. You need to compare each element, not the sequence.

c = [x for x in a if x < b]
like image 28
Ignacio Vazquez-Abrams Avatar answered Nov 13 '22 07:11

Ignacio Vazquez-Abrams