成对统一列表项

时间:2012-12-01 13:48:09

标签: python list-comprehension

给出一个清单

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

使用2n元素

如何获取列表

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

n个元素吗?

3 个答案:

答案 0 :(得分:2)

来自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返回一个迭代器;如果您拥有以获得列表,只需将iterable消费到新列表中:

newlist = list(grouper(2, inputlist))

答案 1 :(得分:2)

a = [1,2,3,4,5,6]
b = [a[i]+a[i+1] for i in xrange(0,len(a),2)]

答案 2 :(得分:2)

li = [1,2,10,20,100,200,2000,3000,2,2,3,3,5,5]
print li

it = iter(li)
if len(li)%2==0:
    print [x+it.next() for x in it]

给出

[1, 2, 10, 20, 100, 200, 2000, 3000, 2, 2, 3, 3, 5, 5]
[3, 30, 300, 5000, 4, 6, 10]