从Python列表列表中过滤元素? [英] filtering elements from list of lists in Python?
问题描述
我想从列表中筛选元素,并使用lambda遍历每个元素的元素.例如,给定列表:
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]]
假设我只想保留列表总和大于N的元素.我尝试编写:
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)
但是我得到了错误:
<lambda>() takes exactly 3 arguments (1 given)
在将每个元素的值分配给x,y和z时如何进行迭代?像zip一样,但列表很长.
How can I iterate while assigning values of each element to x, y, and z? Something like zip, but for arbitrarily long lists.
谢谢
p.s.我知道我可以这样写:filter(lambda x:sum(x)...,a)但这不是重点,想象一下这些不是数字而是任意元素,我想将它们的值赋给变量名. /p>
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.
推荐答案
在我们有其他可用技术时,将lambda
与filter
一起使用是一种愚蠢的做法.
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)]
如果我真的需要一个函数,我可以使用参数元组拆包(顺便说一句,由于人们使用的很少,在Python 3.x中已将其删除):lambda (x, y, z): x + y + z
取一个元组并将其三个拆包. x
,y
和z
的项目. (请注意,您也可以在def
中使用它,即:def f((x, y, z)): return x + y + z
.)
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
.)
您当然可以在所有版本的Python中使用分配样式解压缩(def f(item): x, y, z = item; return x + y + z
)和索引编制(lambda item: item[0] + item[1] + item[2]
).
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.
这篇关于从Python列表列表中过滤元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!