好的,这很有趣 xD。您需要的一切都由 itertools 提供,您只需以正确的方式组合它。看看这个:
import itertools
lst = [1,2,3,4,5]
points = list(itertools.combinations(lst, 2))
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
f = lambda p: filter(lambda sub: not any(x in sub for x in p), points)
res = []
for p in points:
res.extend(list(itertools.product([p], f(p))))
# corresponding list-comprehension solution
# res = list(itertools.chain.from_iterable(itertools.product([p], f(p)) for p in points))
返回:
res = [((1, 2), (3, 4)), ((1, 2), (3, 5)), ((1, 2), (4, 5)), ((1, 3), (2, 4)), ((1, 3), (2, 5)), ((1, 3), (4, 5)), ((1, 4), (2, 3)), ((1, 4), (2, 5)), ((1, 4), (3, 5)), ((1, 5), (2, 3)), ((1, 5), (2, 4)), ((1, 5), (3, 4)), ((2, 3), (1, 4)), ((2, 3), (1, 5)), ((2, 3), (4, 5)), ((2, 4), (1, 3)), ((2, 4), (1, 5)), ((2, 4), (3, 5)), ((2, 5), (1, 3)), ((2, 5), (1, 4)), ((2, 5), (3, 4)), ((3, 4), (1, 2)), ((3, 4), (1, 5)), ((3, 4), (2, 5)), ((3, 5), (1, 2)), ((3, 5), (1, 4)), ((3, 5), (2, 4)), ((4, 5), (1, 2)), ((4, 5), (1, 3)), ((4, 5), (2, 3))]
它基本上归结为itertools.combinations(你已经做过)和itertools.product。扭曲是在两者之间执行的过滤(请参阅f = lambda ...)。如果您在理解代码方面需要进一步帮助,请告诉我。