filtering elements from list of lists in Python?

2019-01-19 23:24发布

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 want to keep only elements where the sum of the list is greater than N. I tried writing:

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

but I get the error:

 <lambda>() takes exactly 3 arguments (1 given)

How can I iterate while assigning values of each element to x, y, and z? Something like zip, but for arbitrarily long lists.

thanks,

p.s. I know I can write this using: filter(lambda x: sum(x)..., a) but that's not the point, imagine that these were not numbers but arbitrary elements and I wanted to assign their values to variable names.

7条回答
聊天终结者
2楼-- · 2019-01-20 00:22

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().

查看更多
登录 后发表回答