Skip to content Skip to sidebar Skip to footer

Filtering Elements From List Of Lists In Python?

I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list: a = [[1,2,3],[4,5,6]] suppose that I wa

Solution 1:

Using lambda with filter is sort of silly when we have other techniques available.

In this case I would probably solve the specific problem this way (or using the equivalent generator expression)

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> [item for item in a if sum(item) > 10]
[[4, 5, 6]]

or, if I needed to unpack, like

>>> [(x, y, z) for x, y, z in a if (x + y) ** z > 30][(4, 5, 6)]

If I really needed a function, I could use argument tuple unpacking (which is removed in Python 3.x, by the way, since people don't use it much): lambda (x, y, z): x + y + z takes a tuple and unpacks its three items as x, y, and z. (Note that you can also use this in def, i.e.: def f((x, y, z)): return x + y + z.)

You can, of course, use assignment style unpacking (def f(item): x, y, z = item; return x + y + z) and indexing (lambda item: item[0] + item[1] + item[2]) in all versions of Python.

Solution 2:

You can explicitly name the sublist elements (assuming there's always a fixed number of them), by giving lambda a tuple as its argument:

>>> a = [[1,2,3],[4,5,6]]
>>> N = 10
>>> filter(lambda (i, j, k): i + j + k > N, a)
[[4, 5, 6]]

If you specify "lambda i, j, k" as you tried to do, you're saying lambda will receive three arguments. But filter will give lambda each element of a, that is, one sublist at a time (thus the error you got). By enclosing the arguments to lambda in parenthesis, you're saying that lambda will receive one argument, but you're also naming each of its components.

Solution 3:

You can do something like

>>> a=[[1,2,3],[4,5,6]]
>>> filter(lambda (x,y,z),: x+y+z>6, a)
[[4, 5, 6]]

Using the deconstruction syntax.

Solution 4:

How about this?

filter(lambda b : reduce(lambda x, y : x + y, b) >= N, a)

This isn't answering the question asked, I know, but it works for arbitrarily-long lists, and arbitrarily-long sublists, and supports any operation that works under reduce().

Solution 5:

Try something like this:

filter(lambda a: a[0] + a[1] + a[2] >= N, a)

Post a Comment for "Filtering Elements From List Of Lists In Python?"