【发布时间】:2009-11-23 15:44:23
【问题描述】:
什么 Python 的用户自定义列表理解结构最有用?
我创建了以下两个量词,用于执行不同的验证操作:
def every(f, L): return not (False in [f(x) for x in L])
def some(f, L): return True in [f(x) for x in L]
下面提出了一个优化版本(需要 Python 2.5+):
def every(f, L): return all(f(x) for x in L)
def some(f, L): return any(f(x) for x in L)
那么,它是如何工作的?
"""For all x in [1,4,9] there exists such y from [1,2,3] that x = y**2"""
answer = every([1,4,9], lambda x: some([1,2,3], lambda y: y**2 == x))
使用此类操作,您可以轻松进行智能验证,例如:
"""There exists at least one bot in a room which has a life below 30%"""
answer = some(bots_in_this_room, lambda x: x.life < 0.3)
等等,您甚至可以使用此类量词回答非常复杂的问题。当然,Python 中没有无限列表(嘿,它不是 Haskell :)),但是 Python 的列表推导非常实用。
你有自己喜欢的列表理解结构吗?
PS:我想知道,为什么大多数人倾向于不回答问题而是批评所提供的示例?问题实际上是关于最喜欢的列表理解构造。
【问题讨论】:
-
社区维基,如果有的话
-
这些函数是从 2.5 开始内置的。 docs.python.org/library/functions.html
-
我意识到它们并不等同。显然,内置函数不允许您传入函数。
-
使用生成器的 Python 中有类似“无限列表”的对象。 itertools.count() 例如返回 0,1,2,3,...
标签: python list list-comprehension