我有此代码:
DATETIME2
这段代码正在生成三对,如下所示:
from collections import Counter
def groups(d, l, c = []):
if l == len(c):
yield c
else:
for i in d:
if i not in c:
_c = Counter([j for k in [*c, i] for j in k])
if all(j < 3 for j in _c.values()):
yield from groups(d, l, c+[i])
data = [(1,2),(2,3),(2,4),(2,5),(2,6),(3,1),(3,2),(3,4)]
result = list(groups(data, 3))
问题是,有这样的重复项:
[[(1, 2), (2, 3), (3, 1)], [(1, 2), (2, 3), (3, 4)], [(1, 2), (2, 4), (3, 1)],1[(1, 2), (2, 4), (3, 4)], [(1, 2), (2, 5), (3, 1)], [(1, 2), (2, 5), (3, 4)] ...
有没有一种方法可以避免它们在生成过程中发生?
答案 0 :(得分:1)
您正在重新发明轮子。只需使用itertools.combinations
:
from itertools import combinations
data = [(1, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4)]
print(list(combinations(data, 3)))
# [((1, 2), (2, 3), (2, 4)), ((1, 2), (2, 3), (2, 5)), ...
您可以通过检查返回列表的长度(即56)来确认没有重复,这正是您所期望的(8选择3等于56)
如果您需要应用自定义逻辑,您仍然可以这样做:
from itertools import combinations
data = [(1, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4)]
wanted_combinations = []
for combination in combinations(data, 3):
# apply logic
if condition:
wanted_combinations.append(combination)