Get a running total from a list

前端 未结 4 1631
青春惊慌失措
青春惊慌失措 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

    Initialize a defaultdict with type int and use the name as the key

    from collections import defaultdict
    name_list = defaultdict(int)
    for line in sys.stdin:
        line = line.strip()
        data = line.split("-")
        name = data[0]
        value = int(data[1])
        name_list[name] += value
    for key, value in name_list.items(): print key, value
    

提交回复
热议问题