对于像这样的列表
a = [1,2,3,4,5]
我想在结果中获取所有两个元素子集,例如:
[((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))]
我写了一个愚蠢的代码,例如:
b=[]
for i in combinations(a,2):
for j in combinations(a,2):
if(set(i).intersection(j)==set()):
b.append((i,j))
谁有好的办法吗?
@insomnia 下面的代码用于生成排列,我认为可以很容易地自定义它以适合您的情况:
import itertools
a = [1,2,3,4,5]
result = []
for combo in itertools.permutations(a, 2):
result.append(combo)
print(len(result))
我是一名优秀的程序员,十分优秀!