如何在列表中查找成对的数字作为给定数字

问题描述 投票:2回答:1

几天前,我遇到一个问题,该问题说有一个数字列表和一个称为total的值。现在,我们需要编写一个给出元组列表(元组中仅2个元素)的程序,每个元组的总和应等于total的值。示例:以下是输入:

input = [1,2,3,4,6,7,8,9] 
total = 10

以下为输出:

output = [(1,9), (2,8), (3,7), (4,6)]
python python-3.x
1个回答
1
投票

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函数。

© www.soinside.com 2019 - 2024. All rights reserved.