📜  Python - 来自其他列表的所有替换组合

📅  最后修改于: 2022-05-13 01:54:20.944000             🧑  作者: Mango

Python - 来自其他列表的所有替换组合

给定一个列表,任务是编写一个Python程序来执行从其他列表到当前列表的所有可能替换。

方法#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))


输出:

方法#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))

输出: