繁体   English   中英

对列表中所有元素求和,除了第一个

[英]sum all the elements in the list of lists except first

添加列表列表中除第一个元素以外的所有元素,并创建一个新列表。

  l = [[u'Security', -604.5, -604.5, -604.5, 
       -302.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2115.75], 
       [u'Medicare', -141.38, -141.38, -141.38, -70.69, 
       0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -494.83], 
       [u'Insurance', -338.0, -338.0, -338.0, -169.0, 0.0, 
       0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1183.0]]

输出应该看起来像

['total',-1083.88,-1083.88,-1083.88,-541.94,0.0,0.0,0.0,0.0,0.0,0.0,
   0.0,0.0,-3793.58]

例如:输出列表的-1083.88 = -604.5 +(-141.38)+(-338.0)=-1083.88

我已经试过了

for i in r:
   del(i[0])
total = [sum(i) for i in zip(*r)]

按照您的预期输出,我相信您正在寻找列的转置和求和。 您可以为此使用zip

r = [sum(x) if not isinstance(x[0], str) else 'total' for x in zip(*l)]

print(r)
['total', -1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]

或者,将转座转换为list ,您可以避免if检查(这类似于MaximTitarenko的answer ,因此也应归功于它们)。

r = [sum(x) for x in list(zip(*l))[1:]]
r.insert(0, 'total')

或者,如果您愿意,

r = ['total'] + [sum(x) for x in list(zip(*l))[1:]]

优雅一点。

您可以尝试以下方法:

result = ['total'] + [sum(el) for el in list(zip(*l))[1:]] 

print(result)
# ['total', -1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]

要使用所有python itertools.islice您需要使用itertools.islice因为在python中, zip()返回迭代器,而您不能仅使用[1:]下标zip对象。

In [1]: l = [[u'Security', -604.5, -604.5, -604.5,
   ...:    ...:        -302.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2115.75
   ...: ],
   ...:    ...:        [u'Medicare', -141.38, -141.38, -141.38, -70.69,
   ...:    ...:        0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -494.83],
   ...:    ...:        [u'Insurance', -338.0, -338.0, -338.0, -169.0, 0.0,
   ...:    ...:        0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1183.0]]
   ...:

In [2]: from itertools import islice

In [3]: total = [sum(new) for new in islice(zip(*l), 1, None)]

In [4]: total
Out[4]:
[-1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]

要包含'total'在乞讨作为cᴏʟᴅsᴘᴇᴇᴅ在评论中指出的亲切

In [5]: ['total'] + total
Out[6]:
    ['total', -1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]

如果您想真正提高效率,可以使用itertools的islice

from itertools import islice, repeat
s = map(sum, zip(*map(islice, l, repeat(1), repeat(None) ) ) )
total = ['total']
total.extend(s)

编辑:对不起,第一次没有阅读整个上下文:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM