Harto Saarinen
Harto Saarinen

Reputation: 143

Selecting elements from list of lists that satisfy a condition

I have the following list

a = [['a', 'b', 1], ['c', 'b', 3], ['c','a', 4], ['a', 'd', 2]]

and I'm trying to remove all the elements from the list where the last element is less than 3. So the output should look like

a = [['c', 'b', 3], ['c','a', 4]]

I tried to use filter in the following way

list(filter(lambda x: x == [_, _, 2], a))

Here _ tries to denote that the element in those places can be anything. I'm used to this kind of syntax from mathematica but I have been unable to find something like this in Python (is there even such a symbol in python ?).

I would prefer solution using map and filter as those are most intuitive for me.

Upvotes: 4

Views: 3177

Answers (3)

Mohammad Azim
Mohammad Azim

Reputation: 2933

a = [['a', 'b', 1], ['c', 'b', 3], ['c','a', 4], ['a', 'd', 2]]

Filter above list with list comprehension like:

b = [x for x in a if x[-1] >= 3]

Upvotes: 0

Jan K
Jan K

Reputation: 4150

List comprehension approach:

a_new = [sublist for sublist in a if sublist[-1] >= 3]

Upvotes: 1

Austin
Austin

Reputation: 26039

You should be using x[-1] >= 3 in lambda to retain all sub lists with last value greater than or equal to 3:

>>> a = [['a', 'b', 1], ['c', 'b', 3], ['c','a', 4], ['a', 'd', 2]]
>>> list(filter(lambda x: x[-1] >= 3, a))
[['c', 'b', 3], ['c', 'a', 4]]

Upvotes: 4

Related Questions