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

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

    This is fairly easy using a dictionary:

    result={} #initialize an empty dictionary
    for (type,cost) in my_list:
        if type not in result.keys():
            result[type]=int(cost[1:]) #add entry
        else:
            result[type]=result[type]+int(cost[1:]) #increment cost
    
    #make dictionary a list again
    dictlist=[]
    for key, value in result.iteritems():
        temp = [key,"$"+str(value)] #add dollar sign
        dictlist.append(temp)
    
    print dictlist
    

    Edit: forgot two lines

提交回复
热议问题