簡體   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