Python|列表中的尺寸范围组合
已经讨论了查找特定大小的列表元素组合的问题。但有时,我们需要更多,我们希望所有大小的元素的所有组合都在 i 和 j 之间。让我们讨论一下可以执行此函数的某些方式。
方法#1:使用列表理解+ combinations()
可以使用列表推导来执行此任务,列表推导可以执行改变组合长度的任务,并且组合()可以执行查找组合的实际任务。
# Python3 code to demonstrate working of
# Size Range Combinations 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))
# initializing i, j
i, j = 2, 4
# Size Range Combinations in list
# Using list comprehension + combinations()
res1 = [com for sub in range(j) for com in combinations(test_list, sub + 1)]
res2 = [com for sub in range(i - 1) for com in combinations(test_list, sub + 1)]
res = list(set(res1) - set(res2))
# Printing result
print("The combinations of elements in range of i and j : " + str(res))
The original list is : [4, 5, 6, 7, 3, 8]
The combinations of elements in range of i and j : [(7, 3), (4, 7), (4, 5, 6, 3), (4, 8), (5, 6), (5, 6, 3), (4, 6, 8), (5, 7, 8), (5, 6, 7, 8), (6, 7, 3), (6, 7, 3, 8), (5, 8), (5, 3, 8), (5, 6, 7), (6, 7), (4, 7, 3, 8), (5, 6, 3, 8), (5, 6, 8), (4, 6, 7, 8), (6, 3), (6, 3, 8), (5, 7, 3, 8), (7, 3, 8), (5, 7, 3), (4, 5, 7, 3), (4, 7, 8), (4, 6, 7), (4, 5, 3), (4, 5), (4, 6, 7, 3), (6, 7, 8), (4, 6, 3, 8), (4, 5, 6, 8), (4, 3, 8), (4, 5, 7, 8), (4, 5, 6), (5, 3), (4, 6, 3), (4, 5, 6, 7), (4, 5, 7), (4, 6), (6, 8), (4, 5, 3, 8), (4, 5, 8), (5, 7), (3, 8), (4, 3), (5, 6, 7, 3), (4, 7, 3), (7, 8)]
方法2:使用循环+ extend() + combinations()
此方法与上述方法类似,只是循环用于迭代组合大小,而 extend() 执行将组合一个接一个地添加到最终结果的任务。
# Python3 code to demonstrate working of
# Size Range Combinations 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))
# initializing i, j
i, j = 2, 4
# Size Range Combinations in list
# Using loop + extend() + combinations()
res = []
for sub in range(j):
if sub >= (i - 1):
res.extend(combinations(test_list, sub + 1))
# Printing result
print("The combinations of elements in range of i and j : " + str(res))
The original list is : [4, 5, 6, 7, 3, 8]
The combinations of elements in range of i and j : [(7, 3), (4, 7), (4, 5, 6, 3), (4, 8), (5, 6), (5, 6, 3), (4, 6, 8), (5, 7, 8), (5, 6, 7, 8), (6, 7, 3), (6, 7, 3, 8), (5, 8), (5, 3, 8), (5, 6, 7), (6, 7), (4, 7, 3, 8), (5, 6, 3, 8), (5, 6, 8), (4, 6, 7, 8), (6, 3), (6, 3, 8), (5, 7, 3, 8), (7, 3, 8), (5, 7, 3), (4, 5, 7, 3), (4, 7, 8), (4, 6, 7), (4, 5, 3), (4, 5), (4, 6, 7, 3), (6, 7, 8), (4, 6, 3, 8), (4, 5, 6, 8), (4, 3, 8), (4, 5, 7, 8), (4, 5, 6), (5, 3), (4, 6, 3), (4, 5, 6, 7), (4, 5, 7), (4, 6), (6, 8), (4, 5, 3, 8), (4, 5, 8), (5, 7), (3, 8), (4, 3), (5, 6, 7, 3), (4, 7, 3), (7, 8)]