给出清单

[1,2,3,4,5,6]


2n元素

我如何获得清单

[1+2,3+4,5+6]


n元素?

最佳答案

itertools recipes section

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)


然后致电:

for paired in grouper(2, inputlist):
    # paired is a tuple of two elements from the inputlist at a time.


grouper返回一个迭代器;如果必须要有一个列表,只需将可迭代对象消耗到一个新列表中:

newlist = list(grouper(2, inputlist))

关于python - 成对统一列表项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13660064/

10-10 19:05