Python|所有可能的 N 个组合元组
有时,在使用Python元组时,我们可能会遇到需要生成所有可能的组合对直到 N 的问题。这可以在数学领域得到应用。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用列表理解 + product()
可以使用列表推导来执行此任务,该列表推导可用于迭代 N 个数字的容器,并且product()
执行从它们形成组合的任务。
Python3
# Python3 code to demonstrate working of
# All possible N combination tuples
# Using list comprehension + product()
from itertools import product
# initialize N
N = 3
# All possible N combination tuples
# Using list comprehension + product()
res = [ele for ele in product(range(1, N + 1), repeat = N)]
# printing result
print("Tuple Combinations till N are : " + str(res))
Python3
# Python3 code to demonstrate working of
# All possible N combination tuples
# Using product()
from itertools import product
# initialize N
N = 3
# All possible N combination tuples
# Using product()
res = list(product(range(1, N + 1), repeat = N))
# printing result
print("Tuple Combinations till N are : " + str(res))
Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
方法 #2:使用product()
此任务也可以通过仅使用单个函数来执行。可以使用转换为列表来消除列表推导的使用。
Python3
# Python3 code to demonstrate working of
# All possible N combination tuples
# Using product()
from itertools import product
# initialize N
N = 3
# All possible N combination tuples
# Using product()
res = list(product(range(1, N + 1), repeat = N))
# printing result
print("Tuple Combinations till N are : " + str(res))
Tuple Combinations till N are : [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]