如果您注意在缩减函数的结果中保留当前项目的副本,则可以使用缩减来实现此目的。
def diff_summarize(revisionList, nextRevision):
'''helper function (adaptor) for using svn.diff_summarize with reduce'''
if revisionList:
# remove the previously tacked on item
r1 = revisionList.pop()
revisionList.append(svn.diff_summarize(
svn_path, revision1=r1, revision2=nextRevision))
# tack the current item onto the end of the list for use in next iteration
revisionList.append(nextRevision)
return revisionList
summaries = reduce(diff_summarize, dm_revisions, [])
编辑: 是的,但没有人说reduce 中的函数结果必须是标量。我将示例更改为使用列表。基本上,最后一个元素总是之前的版本(除了第一次通过),所有前面的元素都是svn.diff_summarize 调用的结果。这样,您将获得一个结果列表作为最终输出...
EDIT2:是的,代码确实被破坏了。我这里有一个可行的假人:
>>> 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.