如何在列表中添加n个连续元素

时间:2012-02-06 18:37:30

标签: python

我的上一个问题是adding two consecutive numbers in a list。但答案并非一般化。如何添加n consecutive elements 一个列表。其中n >= 2

if n = 3

l = [1,2,3,4,5,6] result = [6, 15]
l = [1,2,3,4,5,6,7] result = [6, 15, 7]
l = [1,2,3,4,5,6,7,8] result = [6, 15, 15]

if n = 4

l = [1,2,3,4,5,6,7] result = [10, 18]

6 个答案:

答案 0 :(得分:3)

n=numConsecutiveElements
[sum(list[x:x+n]) for x in range (0,len(list),n)]

会做的伎俩

代码说明

x=0 //Start at the first element
while(x<len(list)): // Until we get to the end of the list
    sum(list[x] + list[x+1] + ... list[x+n-1])  //Sum n elements
    x+=n //Move The first element n elements forward

答案 1 :(得分:2)

def add(seq, n):
    return [sum(seq[i:i + n]) for i in range(0, len(seq), n)]


print(add([1, 2, 3, 4, 5, 6], 3))
print(add([1, 2, 3, 4, 5, 6, 7], 3))
print(add([1, 2, 3, 4, 5, 6, 7, 8], 3))
print(add([1, 2, 3, 4, 5, 6, 7], 4))

答案 2 :(得分:1)

我认为您可以像以前一样做同样的事情,但只需将输入推广到izip_longest

import itertools as it
s = [l[n-i::n] for i in range(n)]
[sum(r) for r in it.izip_longest(*s, fillvalue=0)]

或在一行

f = lambda n,l: [sum(r) for r in it.izip_longest(*[l[i::n] for i in range(n)], fillvalue=0)]

>>>f(3, range(1,7))
[6,15]
>>>f(3, range(1,8))
[6,15, 7]
>>>f(3, range(1,9))
[6,15,15]
>>>f(4, range(1,8))
[10,18]

答案 3 :(得分:1)

使用这个迭代的itertools你可以做到

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

[sum(g) for g in grouper(3, l, 0)]

答案 4 :(得分:0)

使用grouper recipe

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    '''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
From itetools recipes'''
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def get_n_chunks_summed(it,n):
    return [sum(el) for el in grouper(n, it, 0)]

L = [1,2,3,4,5,6,7]
for n in range(1,5):
    print('{0} -> {1}'.format(n,get_n_chunks_summed(L,n)))

输出:

1 -> [1, 2, 3, 4, 5, 6, 7]
2 -> [3, 7, 11, 7]
3 -> [6, 15, 7]
4 -> [10, 18]

答案 5 :(得分:0)

怎么样

print map(sum, zip(*[iter(lst + [0] * (len(lst) % n + 1))] * n))