更新时间:2022-05-27 22:04:45
在我们有其他可用技术时,将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.