【发布时间】:2010-03-03 14:20:25
【问题描述】:
我需要一个函数,它能够迭代集合,以集合元素作为参数调用提供的函数,并在从提供的函数接收到“True”时返回参数或其索引。
是这样的:
def find(f, seq, index_only=True, item_only=False):
"""Return first item in sequence where f(item) == True."""
index = 0
for item in seq:
if f(item):
if index_only:
return index
if item_only:
return item
return index, item
index+= 1
raise KeyError
所以我想知道标准 python 工具集中是否有类似的东西?
【问题讨论】:
-
OP 的 sn-p 是表达需求的更直接(如果只是更长一点)的方式;这可能是规定的方式,视情况而定。然而,从回复中得出了一个非常有用的见解:
regarding loops, when in doubt, consult/consider itertools。
标签: python functional-programming lambda