To sum up values of same items in a list of tuples while they are string

后端 未结 5 688
一整个雨季
一整个雨季 2021-01-23 01:56

If I have list of tuples like this:

my_list = [(\'books\', \'$5\'), (\'books\', \'$10\'), (\'ink\', \'$20\'), (\'paper\', \'$15\'), (\'paper\', \'$20\'), (\'pap         


        
5条回答
  •  无人及你
    2021-01-23 02:43

    You can simply use a dictionary to solve this problem.

    my_list = [('books', '$5'), ('books', '$10'), ('ink', '$20'),
           ('paper', '$15'), ('paper', '$20'), ('paper', '$15')]
    
    sums = {}
    for item, price in my_list:
        sums[item] = sums.get(item, 0) + int(price[1:])
    
    print sums
    

    And if you need list of tuples, just do

    print sums.items()
    

    And to get your the output you expect,

    print [(item, '$' + str(price)) for item, price in sums.items()]
    

    Update

    If you have costs with floating point value, you can simply change int to float like this and rest of the code remains the same,

    sums[item] = sums.get(item, 0) + float(price[1:])
    

提交回复
热议问题