2012-02-06 3 views

답변

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

또는 itertools이 reciepe를 사용하여 한 줄

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
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 
+0

왜 downvote? 이 솔루션에 문제가 있습니까? – RussS

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

에 당신은

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)] 
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] 
0

방법에 대한

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