【问题标题】:How to compute the accumulative sum of a list of tuples如何计算元组列表的累积和
【发布时间】:2016-07-23 12:05:27
【问题描述】:

我有这个元组列表,想用之前列表索引的累计和创建一个新列表:

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

我正在使用:

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)

两种情况(zipoperator)都返回

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

【问题讨论】:

    标签: python list python-3.x tuples


    【解决方案1】:

    你可以使用itertools.accumulate:

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

    它接受一个可选的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)]
    

    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
    

    【讨论】:

    • 哦,我忘了说:python 2.7 需要这个。 Itertools 累积似乎仅在 3.x 中有效
    • @verto,您的问题被标记为python-3.x
    • @verto,我为你添加了函数accumulate
    【解决方案2】:

    NVM,可以用这段代码解决:

        result1=0
        result2=0
        l1=[]
        for k, v in l:
            result1+=k
            result2+=v
            l1.append((result1, result2))
    

    非常感谢您的帮助! =)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2021-05-11
      • 2020-09-26
      • 2013-05-26
      • 2020-12-17
      • 2013-01-26
      相关资源
      最近更新 更多