如果你在减少函数的结果中保留当前项的副本,那么可以使用Reduce来实现这个目的。
def diff_summarize(revisionList, nextRevision):
'''helper function (adaptor) for using svn.diff_summarize with reduce'''
if revisionList:
r1 = revisionList.pop()
revisionList.append(svn.diff_summarize(
svn_path, revision1=r1, revision2=nextRevision))
revisionList.append(nextRevision)
return revisionList
summaries = reduce(diff_summarize, dm_revisions, [])
编辑:是的,但没有人说reduce
函数中的结果必须是标量。我改变了我的示例以使用列表。基本上,最后一个元素始终是先前修订版(除了第一次通过),所有前面的元素都是svn.diff_summarize
调用的结果。这样,您将获得一个结果列表作为最终输出...
编辑2:是的,代码确实有问题。我这里有一个可行的虚拟代码:
>>> def compare(lst, nxt):
... if lst:
... prev = lst.pop()
... lst.append((prev, nxt))
... lst.append(nxt)
... return lst
...
>>> reduce(compare, "abcdefg", [])
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g'), 'g']
这在shell中进行了测试,正如您所看到的。您需要将compare
中lst.append
调用中的(prev, nxt)
替换为实际将调用摘要附加到svn.diff_summarize
的内容。
>>> help(reduce)
Help on built-in function reduce in module __builtin__:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.