Python|直到列表中大小为 N 的元素组合
已经讨论了查找特定大小的列表元素组合的问题。但有时,我们需要更多,我们希望拥有所有大小的元素的所有组合直到 N。让我们讨论可以执行此函数的某些方式。
方法#1:使用列表理解+ combinations()
可以使用列表推导来执行此任务,列表推导可以执行改变组合长度的任务,并且combination()
可以执行查找组合的实际任务。
# Python3 code to demonstrate working of
# Combinations of elements till size N in list
# Using list comprehension + combinations()
from itertools import combinations
# initializing list
test_list = [4, 5, 6, 7, 3, 8]
# printing original list
print("The original list is : " + str(test_list))
# Combinations of elements till size N in list
# Using list comprehension + combinations()
res = [com for sub in range(3) for com in combinations(test_list, sub + 1)]
# Printing result
print("The combinations of elements till length N : " + str(res))
The original list is : [4, 5, 6, 7, 3, 8]
The combinations of elements till length N : [(4, ), (5, ), (6, ), (7, ), (3, ), (8, ), (4, 5), (4, 6), (4, 7), (4, 3), (4, 8), (5, 6), (5, 7), (5, 3), (5, 8), (6, 7), (6, 3), (6, 8), (7, 3), (7, 8), (3, 8), (4, 5, 6), (4, 5, 7), (4, 5, 3), (4, 5, 8), (4, 6, 7), (4, 6, 3), (4, 6, 8), (4, 7, 3), (4, 7, 8), (4, 3, 8), (5, 6, 7), (5, 6, 3), (5, 6, 8), (5, 7, 3), (5, 7, 8), (5, 3, 8), (6, 7, 3), (6, 7, 8), (6, 3, 8), (7, 3, 8)]
方法2:使用循环+ extend() + combinations()
此方法与上述方法类似,只是循环用于迭代组合大小,而 extend() 执行将组合一个接一个地添加到最终结果的任务。
# Python3 code to demonstrate working of
# Combinations of elements till size N in list
# Using loop + extend() + combinations()
from itertools import combinations
# initializing list
test_list = [4, 5, 6, 7, 3, 8]
# printing original list
print("The original list is : " + str(test_list))
# Combinations of elements till size N in list
# Using loop + extend() + combinations()
res = []
for sub in range(3):
res.extend(combinations(test_list, sub + 1))
# Printing result
print("The combinations of elements till length N : " + str(res))
The original list is : [4, 5, 6, 7, 3, 8]
The combinations of elements till length N : [(4, ), (5, ), (6, ), (7, ), (3, ), (8, ), (4, 5), (4, 6), (4, 7), (4, 3), (4, 8), (5, 6), (5, 7), (5, 3), (5, 8), (6, 7), (6, 3), (6, 8), (7, 3), (7, 8), (3, 8), (4, 5, 6), (4, 5, 7), (4, 5, 3), (4, 5, 8), (4, 6, 7), (4, 6, 3), (4, 6, 8), (4, 7, 3), (4, 7, 8), (4, 3, 8), (5, 6, 7), (5, 6, 3), (5, 6, 8), (5, 7, 3), (5, 7, 8), (5, 3, 8), (6, 7, 3), (6, 7, 8), (6, 3, 8), (7, 3, 8)]