Python程序在给定条件下查找列表中的所有组合
给定一个列表,其中一些元素是可选元素的列表。任务是从所有选项中找到所有可能的组合。
例子:
Input : test_list = [“geekforgeeks”, [5, 4, 3], “is”, [“best”, “good”, “better”]], K = 3
Output : [[‘geekforgeeks’, 5, ‘is’, ‘best’], [‘geekforgeeks’, 4, ‘is’, ‘good’], [‘geekforgeeks’, 3, ‘is’, ‘better’]]
Explanation : Inner elements picked and paired with similar indices. 5 -> “best”.
Input : test_list = [“geekforgeeks”, [5, 4], “is”, [“best”, “good”]], K = 2
Output : [[‘geekforgeeks’, 5, ‘is’, ‘best’], [‘geekforgeeks’, 4, ‘is’, ‘good’]]
Explanation : Inner elements picked and paired with similar indices. 5 -> “best”.
方法:使用循环
在此,我们使用嵌套循环从每个嵌套选项列表中获取索引组合,然后使用外部循环获取所有组合中的默认值。
Python3
# Python3 code to demonstrate working of
# Optional Elements Combinations
# Using loop
# initializing list
test_list = ["geekforgeeks", [5, 4, 3, 4], "is",
["best", "good", "better", "average"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing size of inner Optional list
K = 4
res = []
cnt = 0
while cnt <= K - 1:
temp = []
# inner elements selections
for idx in test_list:
# checks for type of Elements
if not isinstance(idx, list):
temp.append(idx)
else:
temp.append(idx[cnt])
cnt += 1
res.append(temp)
# printing result
print("All index Combinations : " + str(res))
输出:
The original list is : [‘geekforgeeks’, [5, 4, 3, 4], ‘is’, [‘best’, ‘good’, ‘better’, ‘average’]]
All index Combinations : [[‘geekforgeeks’, 5, ‘is’, ‘best’], [‘geekforgeeks’, 4, ‘is’, ‘good’], [‘geekforgeeks’, 3, ‘is’, ‘better’], [‘geekforgeeks’, 4, ‘is’, ‘average’]]