Python - N 大小增加列表的列表
给定整数 N 和 M,构造递增列表直到 M,每个列表为 N 大小,即所有组合列表。
Input : N = 2, M = 3
Output : [(1, 2), (1, 3), (2, 3)]
Explanation : Increasing paired elements.
Input : N = 1, M = 4
Output : [(1, ), (2, ), (3, ), (4, )]
Explanation : Increasing paired elements.
方法#1:使用循环
这是可以执行此任务的一种蛮力方式。在此我们迭代元素直到 M,并形成 N 大小的列表。缺点是我们仅限于有限大小的列表。
Python3
# Python3 code to demonstrate working of
# List of N size increasing lists
# Using loop
# initializing N
N = 2
# initializing M
M = 4
# outer loop manages lists
res = []
for idx in range(1, M):
# inner loop manages inner elements
for j in range(idx + 1, M + 1):
res.append((idx, j))
# printing result
print("The constructed combinations : " + str(res))
Python3
# Python3 code to demonstrate working of
# List of N size increasing lists
# Using combinations()
from itertools import combinations
# initializing N
N = 2
# initializing M
M = 4
# using combinations to perform task
res = list(combinations(list(range(1, M + 1)), N))
# printing result
print("The constructed combinations : " + str(res))
输出
The constructed combinations : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
方法#2:使用组合()
这是内置函数,提供此解决方案所需的确切功能。解决了越来越多的列表的问题。
Python3
# Python3 code to demonstrate working of
# List of N size increasing lists
# Using combinations()
from itertools import combinations
# initializing N
N = 2
# initializing M
M = 4
# using combinations to perform task
res = list(combinations(list(range(1, M + 1)), N))
# printing result
print("The constructed combinations : " + str(res))
输出
The constructed combinations : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]