我如何连续加总列表列表的第4个元素(python)

时间:2015-05-23 19:52:25

标签: python

我有这个:

lst=[['Lisboa', 36.751510873830824, 204.31859739607566, '3'],
    ['Madrid', 520.8624708804804, 392.9722807116641, '2'],
    ['Copenhaga', 1971.3230985689115, 2086.416520356296, '5'],
    ['Berlin', 2046.6589661942558, 1735.7426148990855, '4']]

并希望收到此信息:

[['Lisboa', 36.751510873830824, 204.31859739607566, '3'],
['Madrid', 520.8624708804804, 392.9722807116641, '5'],
['Copenhaga', 1971.3230985689115, 2086.416520356296, '10'],
['Berlin', 2046.6589661942558, 1735.7426148990855, '14']]

希望在这里得到一些帮助!!

2 个答案:

答案 0 :(得分:0)

这可能是一个值得怀疑的模式,但是:

 summed = 0
 for inner_list in outer_list:
      summed += inner_list[3]
      inner_list[3] = summed

如果你想出于某种原因保留字符串:

 summed = 0
 for inner_list in outer_list:
      summed += int(inner_list[3])
      inner_list[3] = str(summed)

答案 1 :(得分:-1)

目前尚不清楚你是否需要***在初始值3附近。如果这些是粗体数字失败的尝试,你需要字符串格式的数字,那么试试:

cumsum = 0
for i in lst:
    cumsum += int(i[3])
    i[3] = str(cumsum)

>>> lst
[['Lisboa', 36.751510873830824, 204.31859739607566, '3'],
 ['Madrid', 520.8624708804804, 392.9722807116641, '5'],
 ['Copenhaga', 1971.3230985689115, 2086.416520356296, '10'],
 ['Berlin', 2046.6589661942558, 1735.7426148990855, '14']]