简体   繁体   中英

how do i merge 2d lists with the same named object and add there values together in a new list?

i would like to know how to combine data in multiple lists, i have combined them in a way so that they all congregate in the same [] but there are objects with the same name and different values that i want to combine the values and only have one object representing it. basically how do i combine the two "bananas" objects?在此处输入图像描述

i havent tried anything that has worked because i cant find anything specifically related to my issue, i understand that its simple i just cannot find a specific enough answer.

You can use

fruit = [['apple', 5], ['pears', 10], ['bananas', 12]]
items = [['cars', 3], ['sheets', 5], ['bananas', 8]]
colors = [['blue', 3], ['black', 5], ['orange', 8]]
merge = fruit + items + colors
result = set(
    (item, sum(quantity for label, quantity in merge if label == item))
    for item, _ in merge
)
result

Output

{('apple', 5),
 ('bananas', 20),
 ('black', 5),
 ('blue', 3),
 ('cars', 3),
 ('orange', 8),
 ('pears', 10),
 ('sheets', 5)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM