Python程序:查找列表中满足给定条件的所有组合


当需要查找列表中满足特定条件的所有组合时,可以使用简单的迭代、`isinstance` 方法、`append` 方法和索引。

示例

以下是演示:

Open Compiler
print("Method definition begins") def merge_the_vals(my_list_1, my_list_2, K): index_1 = 0 index_2 = 0 while(index_1 < len(my_list_1)): for i in range(K): yield my_list_1[index_1] index_1 += 1 for i in range(K): yield my_list_2[index_2] index_2 += 1 print("Method definition ends") my_list_1 = [12, 56, 14, 28, 61, 73, 59, 90] my_list_2 = [52, 16, 17, 34, 43, 16, 84, 57] print("The first list is : " ) print(my_list_1) print("The second list is : " ) print(my_list_2) K = 1 print("The value of K is ") print(K) my_result = [element for element in merge_the_vals(my_list_1, my_list_2, K)] print("The resultant list is : ") print(my_result) print("The list after sorting is : " ) my_result.sort() print(my_result)

输出

Method definition begins
Method definition ends
The first list is :
[12, 56, 14, 28, 61, 73, 59, 90]
The second list is :
[52, 16, 17, 34, 43, 16, 84, 57]
The value of K is
2
The resultant list is :
[12, 56, 52, 16, 14, 28, 17, 34, 61, 73, 43, 16, 59, 90, 84, 57]
The list after sorting is :
[12, 14, 16, 16, 17, 28, 34, 43, 52, 56, 57, 59, 61, 73, 84, 90]

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

解释

  • 定义了一个方法,该方法将两个列表和一个 K 值作为参数。

  • 根据索引值和列表长度,`yield` 运算符用于返回结果。

  • 在方法外部,定义了两个整数列表,并在控制台上显示。

  • 定义 K 值并在控制台上显示。

  • 使用列表推导式,调用该方法并传递所需的参数。

  • 将其赋值给结果。

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

  • 使用 sort 方法对结果进行排序,并在控制台上显示。

更新于:2021年9月13日

518 次查看

开启您的职业生涯

完成课程获得认证

开始学习
广告