Skip to main content
 首页 » 编程设计

python之成对统一列表项

2025年05月04日20pengyingh

给定一个列表

[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))