如果我在 Python 中减少一个集合,那么获取集合的其余部分(未访问的项目)的最有效方法是什么?我经常需要对一个集合进行归约,但我希望我的归约函数能够获取我正在归约的集合中未访问的项目。
编辑-澄清一下,我想要类似的东西:
reduce(lambda to-return, item, rest: (code here), collection, initial)
rest 是我的 lambda 尚未看到的项目
这是我能做的最好的。它期望“集合”是可切片的:
def myreduce(func,collection,*args):
"""func takes 3 parameters. The previous value,
the current value, and the rest of the collection"""
def new_func(x,y):
try:
return func(x[1],y[1],collection[y[0]:])
except TypeError:
return func(x,y[1],collection[y[0]:])
return reduce(new_func,enumerate(collection),*args)
print myreduce(lambda x,y,rest:x+y+sum(rest),range(30))
请注意,这是非常糟糕的测试。在您尝试在任何实际代码中使用它之前,请彻底测试。如果您真的希望它适用于任何可迭代对象,您可以collection = tuple(collection)
在顶部放一个我想(假设您有足够的内存可以一次将整个可迭代对象存储在内存中)