简体   繁体   English

从元组列表中查找元组元素总和的所有组合

[英]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.我想生成一个 new_tuple_list,其中包含给定元组列表中元素 2 和元素 3 的所有可能总和。 Element 2 and 3 will be int.元素 2 和 3 将是 int。

Input:输入:

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

Expected output:预计 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. itertools.combinations是此作业的 function。 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. for 循环用于演示目的,但如果需要,您也可以使用列表理解或map()

Notice that this results in new_tuple_list having 4 elements, including (4, 70) for adding 'item1' and 'item3'.请注意,这会导致new_tuple_list具有 4 个元素,包括用于添加“item1”和“item3”的 (4, 70)。 I hope this is the intended behavior.我希望这是预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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