2012-02-06 61 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這個rec​​iepe一行

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 2012-02-06 19:01:03

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