如何计算元组列表的累积和

ver*_*rto 4 python tuples list python-3.x

我有这个元组列表,并希望创建一个新的列表,具有以前列表索引的累积总和:

List = [(1.0, 1.0), (3.0, 3.0), (5.0, 5.0)]

newList = [(1.0, 1.0), (4.0, 4.0), (9.0, 9.0)]
Run Code Online (Sandbox Code Playgroud)

我正在使用:

l1 = []
for j in l: #already a given list
    result = tuple(map(sum, zip(j, j+1)))
    #or
    result = (map(operator.add, j, j+1,))
    l1.append(result)
Run Code Online (Sandbox Code Playgroud)

两种情况(zipoperator)都返回

"TypeError:只能将元组(不是"int")连接到元组"

fal*_*tru 5

你可以使用itertools.accumulate:

>>> import itertools
>>> itertools.accumulate([1, 3, 5])
<itertools.accumulate object at 0x7f90cf33b188>
>>> list(_)
[1, 4, 9]
Run Code Online (Sandbox Code Playgroud)

它接受一个func用于添加的可选项:

>>> lst = [(1.0, 1.0), (3.0, 3.0), (5.0, 5.0)]
>>> import itertools
>>> list(itertools.accumulate(lst, lambda a, b: tuple(map(sum, zip(a, b)))))
[(1.0, 1.0), (4.0, 4.0), (9.0, 9.0)]
Run Code Online (Sandbox Code Playgroud)

itertools.accumulate在Python 3.2中引入.如果使用较低版本,请使用以下内容accumulate(来自功能文档):

import operator
def accumulate(iterable, func=operator.add):
    it = iter(iterable)
    try:
        total = next(it)
    except StopIteration:
        return
    yield total
    for element in it:
        total = func(total, element)
        yield total
Run Code Online (Sandbox Code Playgroud)

  • @verto,你的问题用[tag:python-3.x]标记. (3认同)