简体   繁体   中英

Finding all combination of sum of tuple element from a list of tuple

I want to to generate a new_tuple_list that contains all possible sum of element 2, and element 3 from a given list of tuple. Element 2 and 3 will be int.

Input:

tuple_list = [('item1', 2, 20), ('item2', 3, 20), ('item3', 2, 50)]

Expected output:

new_tuple_list = [(5, 40),(7, 90), (5, 70)]
new_tuple_list = [(2 + 3, 20 +20), (2 + 3 +2 , 20 +20 + 50), (3 + 2,20 + 50)

itertools.combinations is the function for this job. You can use it as

from itertools import combinations
new_tuple_list = []
for k in range(2, len(tuple_list)+1):
    for combination in combinations(tuple_list, k):
        e1, e2 = 0, 0
        for element in combination:
            text, int1, int2 = element
            e1 += int1
            e2 += int2
        new_tuple_list.append((e1, e2))

for loop was used for demonstration purposes, but you could also use list comprehension or map() if you want.

Notice that this results in new_tuple_list having 4 elements, including (4, 70) for adding 'item1' and 'item3'. I hope this is the intended behavior.

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