Get a running total from a list

前端 未结 4 1632
青春惊慌失措
青春惊慌失措 2021-01-28 02:51

I\'m reading in items:

for line in sys.stdin:
    line = line.strip()
    data = line.split(\"-\")

If I print data as it is read,

4条回答
  •  时光取名叫无心
    2021-01-28 02:58

    I recommend creating a dictonary and updating that as you go. I have assumed your data format for data is a list of lists.

    finalList = {}
    
    for name, value in data:
        if name in finalList.keys():
            finalList[name] = finalList[name] + int(value)
        else:
            finalList[name] = int(value)
    
    print(finalList)
    

提交回复
热议问题