你似乎想要得到:每个序列的第一个元素的列表,可以是[s[0] for s in sequences],并且
每个序列的剩余元素的列表,可以是[s[1:] for s in sequences]。在
总共:def accumulate(op, init, seq):
if not seq:
return init
else:
return op(seq[0], accumulate(op, init, seq[1:]))
def accumulate_n(op, init, sequences):
if (not sequences) or (not sequences[0]):
return type(sequences)()
else:
heads = [s[0] for s in sequences]
tails = [s[1:] for s in sequences]
return ([accumulate(op, init, heads)]
+ accumulate_n(op, init, tails))
但是,为了它的价值,我将按行而不是按列执行,并要求init本身是一个序列:
^{pr2}$
清洁要求:def accumulate_n(op, init, sequences):
for s in sequences:
init = [op(x, y) for x, y in zip(init, s)]
return init
最后,使用functools.reduce:def zipper(op):
return lambda xs, ys: [op(x, y) for x, y in zip(xs, ys)]
def accumulate_n(op, init, sequences):
return reduce(zipper(op), sequences, init)