Python中元组列表内元组求和的组合
如果需要获取元组列表中元组的求和组合,可以使用`combinations`方法和列表推导式。
`combinations`方法返回从作为输入传递的可迭代对象中选择的长度为`r`的元素子序列。组合以字典序显示。组合元组按排序顺序显示。
列表可以用来存储异构值(即任何数据类型的数据,例如整数、浮点数、字符串等)。
元组列表基本上包含在一个列表中包含的元组。
下面是一个演示:
示例
from itertools import combinations my_list = [( 67, 45), (34, 56), (99, 123), (10, 56)] print ("The list of tuple is : " ) print(my_list) my_result = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(my_list, 2)] print("The summation combination result is : ") print(my_result)
输出
The list of tuple is : [(67, 45), (34, 56), (99, 123), (10, 56)] The summation combination result is : [(101, 101), (166, 168), (77, 101), (133, 179), (44, 112), (109, 179)]
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
- 定义了一个元组列表,并在控制台上显示。
- 使用`combinations`方法返回长度为2的子序列,如方法中所述。
- 迭代元组列表,并将元组列表中每个元组的元素添加到下一个元组的元素中。
- 此值被赋值给一个变量。
- 此变量是显示在控制台上的输出。
广告