Get a running total from a list

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

    Use a collections.Counter() to count the occurrences:

    import collections
    
    lines = [['Adam', '5'],
             ['Peter', '7'],
             ['Adam', '8'],
             ['Lucy', '2'],
             ['Peter', '4']]
    
    counter = collections.Counter()
    for data in lines:
        counter[data[0]] += int(data[1])
    
    print(counter)
    

    You'll get:

    Counter({'Adam': 13, 'Peter': 11, 'Lucy': 2})
    

提交回复
热议问题