说我们有一个l
列表,它由5个或更多元素组成,我想像斐波那契序列一样,计算列表中的每n个和]
l=[1,5,6,7,2]
最后,我希望有一个新列表l2
,它显示l
列表中每n个元素的总和
1+5=6
5+6=11
6+7=13
7+2=9
l2=[0,6,11,13,9]
我尝试过list2= [sum(l[i:i+i[2]])for i in range(0,len(l),2)]
,但它说int not scriptable
而且我尝试了更多只是为了卡住,请帮助
使用itertools.tee
和pairwise
的一种方法:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
[0, *map(sum, pairwise(l))]
输出:
[0, 6, 11, 13, 9]