我需要一個函數,它能夠遍歷集合,以收集的元素作爲參數調用提供的函數,並在從提供的函數接收到「True」時返回參數或其索引。Python - 功能性「查找」?
據somethong這樣的:
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
所以我想知道是否有像在非標準蟒蛇工具集什麼?
該OP的片段是更直接(如果只是更長一點)的方式來表達的要求;這可能是規定的方式,取決於具體情況。然而,從答覆中得出一個非常有用的見解:「關於循環,如有疑問,請諮詢/考慮itertools'。 – mjv 2010-03-03 14:43:51