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

后端 未结 5 687
一整个雨季
一整个雨季 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:38

    You can use defaultdict to do this:

    >>> from collections import defaultdict
    >>> my_list = [('books', '$5'), ('books', '$10'), ('ink', '$20'), ('paper', '$15'), ('paper', '$20'), ('paper', '$15')] 
    >>> res = defaultdict(list)
    >>> for item, price in my_list:
    ...     res[item].append(int(price.strip('$')))
    ... 
    >>> total = [(k, "${}".format(sum(v))) for k, v in res.items()]
    >>> total
    [('ink', '$20'), ('books', '$15'), ('paper', '$50')]
    

提交回复
热议问题