Py学习  »  Python

有没有一种方法可以像python中的fibonacci序列那样对每n个列表进行求和并成为一个新列表?

Farhan Jamil • 5 年前 • 1568 次点击  

假设我们有一个 l 列表,它由5个或更多的元素组成,我想像斐波那契数列一样计算列表中的每N个和

l=[1,5,6,7,2]

最后我想要一份新的名单 l2 它显示了 列表

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 我试了更多只是为了坚持请帮忙

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52455
 
1568 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Chris
Reply   •   1 楼
Chris    5 年前

单向使用 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]
han solo
Reply   •   2 楼
han solo    5 年前

你可以做一个 list 理解来自 zip 就像,

>>> l
[1, 5, 6, 7, 2]
>>> [0] + [x+y for x,y in zip(l, l[1:])]
[0, 6, 11, 13, 9]

或者不是列表理解,而是像,

>>> [0, *(x+y for x,y in zip(l, l[1:]))]
[0, 6, 11, 13, 9]