Python 程序来获取具有给定求和的 K 长度组


当需要获取具有给定求和的“K”长度组时,可以使用空列表,“product”方法,“sum”方法和“append”方法。

示例

以下是对同一示例的说明

Open Compiler
from itertools import product my_list = [45, 32, 67, 11, 88, 90, 87, 33, 45, 32] print("The list is : ") print(my_list) N = 77 print("The value of N is ") print(N) K = 2 print("The value of K is ") print(K) my_result = [] for sub in product(my_list, repeat = K): if sum(sub) == N: my_result.append(sub) print("The result is : " ) print(my_result)

输出

The list is :
[45, 32, 67, 11, 88, 90, 87, 33, 45, 32]
The value of N is
77
The value of K is
2
The result is :
[(45, 32), (45, 32), (32, 45), (32, 45), (45, 32), (45, 32), (32, 45), (32, 45)]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 将必需的包导入到环境中。

  • 定义一个列表并在控制台上显示该列表。

  • 定义 N 和 K 的值并在控制台上显示该值。

  • 定义一个空列表。

  • 确定列表中元素的乘积,然后检查其是否等于 N。

  • 如果是,则将其附加到空列表中。

  • 这在控制台上显示为输出。

更新于: 21-9 月-2021

149 浏览量

开启你的 职业生涯

完成课程获得认证

开始
广告