几天前,我遇到一个问题,该问题说有一个数字列表和一个称为total的值。现在,我们需要编写一个给出元组列表(元组中仅2个元素)的程序,每个元组的总和应等于total的值。示例:以下是输入:
input = [1,2,3,4,6,7,8,9]
total = 10
以下为输出:
output = [(1,9), (2,8), (3,7), (4,6)]
与itertools.combinations
一起使用列表理解:
itertools.combinations
请注意,您不应使用>>> import itertools
>>> inpt = [1,2,3,4,6,7,8,9]
>>> total = 10
>>> [p for p in itertools.combinations(inpt, 2) if sum(p) == total]
[(1, 9), (2, 8), (3, 7), (4, 6)]
作为变量名,因为它会遮盖内置input
函数。