列表列表中元素的总和

时间:2018-06-22 00:00:00

标签: python

我有一个这样的列表:

list =[['x',1,2,3],['y',2,5,4],['z',6,2,1]...]

如何求和并替换列表的特定元素,以便:

>>>list =[['x',1,2,3],['y',3,7,7],['z',9,9,8]...]
  

编辑:

     

好奇为什么不赞成?!更新:我尝试了@Sunitha解决方案,但   在itertools中不累积-可能是因为运行2.7。我还想出了:

    temp = [0,0,0]
    for i, item in enumerate(list):
        temp = [temp[0]+item[1], temp[1]+item[2],temp[2] + item[3]]
        list[i] = [item[0],temp[0],temp[1],temp[2]]
  

笨拙,但无论如何,我是生物学家。向更多pythonian开放   答案!

2 个答案:

答案 0 :(得分:1)

  

更新:我尝试了@Sunitha解决方案,但是itertools中没有积累-可能是因为运行2.7。

我已经使用Python 2.7.15和Python 3.6.5测试了此代码。此代码从列表中的第二个子列表(索引1,如果适用)开始,向后看前一个子列表,以累积值,如您的示例一样。

Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hmm = [['x', 1, 2, 3], ['y', 2, 5, 4], ['z', 6, 2, 1]]
>>> for i in range(1, len(hmm)):
...     prev = hmm[i - 1][1:]
...     current = iter(hmm[i])
...     hmm[i] = [next(current)] + [a + b for a, b in zip(prev, current)]
... 
>>> hmm
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]

它在Python 3中的编写也可能略有不同:

Python 3.6.5 (default, Jun 14 2018, 13:19:33) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hmm = [['x', 1, 2, 3], ['y', 2, 5, 4], ['z', 6, 2, 1]]
>>> for i in range(1, len(hmm)):
...     _, *prev = hmm[i - 1]
...     letter, *current = hmm[i]
...     hmm[i] = [letter] + [a + b for a, b in zip(prev, current)]
... 
>>> hmm
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]

答案 1 :(得分:0)

简单的单线

>>> from itertools import accumulate
>>> ll=[['x',1,2,3],['y',2,5,4],['z',6,2,1]]
>>>
>>> list(accumulate(ll, lambda *l: [l[-1][0]] + [sum(r) for r in list(zip(*l))[1:]]))
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]

说明

大部分工作由accumulate(ll, func)代码完成,该代码对可迭代func的每个元素运行ll,并带有先前计算的结果。我们只需要执行需要做的功能func

考虑一下,列表的前2个元素

>>> l1=ll[0]; l2=ll[1]
>>> 
>>> l1
['x', 1, 2, 3]
>>> l2
['y', 2, 5, 4]

>>> # A simple zip would create pairs of elements from l1 and l2
>>> f = lambda *l: [list(zip(*l))]
>>> f(l1, l2)
[[('x', 'y'), (1, 2), (2, 5), (3, 4)]]
>>> 
>>> # Remove the first element, so we can calc sum
>>> f = lambda *l: [list(zip(*l))[1:]]
>>> f(l1, l2)
[[(1, 2), (2, 5), (3, 4)]]
>>> 
>>> # Calculate sum for the pairs
>>> f = lambda *l: [sum(r) for r in list(zip(*l))[1:]]
>>> f(l1, l2)
[3, 7, 7]
>>> 
>>> # Now add back the removed first element, but only once
>>> f = lambda *l: [l[-1][0]] + [sum(r) for r in list(zip(*l))[1:]]
>>> f(l1, l2)
['y', 3, 7, 7]

就这样。现在输入此函数以累积

>>> list(accumulate(ll, f))
[['x', 1, 2, 3], ['y', 3, 7, 7], ['z', 9, 9, 8]]