Python - 来自其他列表的所有替换组合
给定一个列表,任务是编写一个Python程序来执行从其他列表到当前列表的所有可能替换。
Input : test_list = [4, 1, 5], repl_list = [8, 10]
Output : [(4, 1, 5), (4, 1, 8), (4, 1, 10), (4, 5, 8), (4, 5, 10), (4, 8, 10), (1, 5, 8), (1, 5, 10), (1, 8, 10), (5, 8, 10)]
Explanation : All elements are replaced by 0 or more elements from 2nd list
Input : test_list = [4, 1], repl_list = [8, 10]
Output : [(4, 1), (4, 8), (4, 10), (1, 8), (1, 10), (8, 10)]
Explanation : All elements are replaced by 0 or more elements from 2nd list
方法#1:使用组合() + len()
在这里,我们使用组合()和len()来执行构造合并列表的组合的任务,用于将输出的大小限制为初始列表的长度。
Python3
# Python3 code to demonstrate working of
# All replacement combination from other list
# Using combinations() + len()
from itertools import combinations
# initializing list
test_list = [4, 1, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing replacement list
repl_list = [8, 10]
# using combinations() to get all combinations replacements
res = list(combinations(test_list + repl_list, len(test_list)))
# printing result
print("All combinations replacements from other list : " + str(res))
Python3
# Python3 code to demonstrate working of
# All replacement combination from other list
# Using combinations() + extend()
from itertools import combinations
# initializing list
test_list = [4, 1, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing replacement list
repl_list = [8, 10]
# using combinations() to get all combinations replacements
# extend() for concatenation
n = len(test_list)
test_list.extend(repl_list)
res = list(combinations(test_list, n))
# printing result
print("All combinations replacements from other list : " + str(res))
输出:
The original list is : [4, 1, 5]
All combinations replacements from other list : [(4, 1, 5), (4, 1, 8), (4, 1, 10), (4, 5, 8), (4, 5, 10), (4, 8, 10), (1, 5, 8), (1, 5, 10), (1, 8, 10), (5, 8, 10)]
方法#2:使用组合() +扩展()
在此,我们使用extend() 执行连接列表的任务,其余功能与上述方法类似。
蟒蛇3
# Python3 code to demonstrate working of
# All replacement combination from other list
# Using combinations() + extend()
from itertools import combinations
# initializing list
test_list = [4, 1, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing replacement list
repl_list = [8, 10]
# using combinations() to get all combinations replacements
# extend() for concatenation
n = len(test_list)
test_list.extend(repl_list)
res = list(combinations(test_list, n))
# printing result
print("All combinations replacements from other list : " + str(res))
输出:
The original list is : [4, 1, 5]
All combinations replacements from other list : [(4, 1, 5), (4, 1, 8), (4, 1, 10), (4, 5, 8), (4, 5, 10), (4, 8, 10), (1, 5, 8), (1, 5, 10), (1, 8, 10), (5, 8, 10)]