我想在列表中的每对元素之间进行比较,而不是以下内容: 差值= [1,2,3,4,5,6]
所以答案是[1,2],[1,3],[1,4],[1,5],[1,6],[2,3],[4,5], [5,6],[3,4],[2,4],[2,5],[3,6],[2,6],[3,5],[4,6] 到目前为止我写过这个,但我正在寻找一种更快的方法。
for i in DIFFERENCE:
for j in DIFFERENCE:
if(some condition and i!=j and i+'_'+j not in COMPARISON and j+'_'+i not in COMPARISON):
COMPARISON.append(i+'_'+j);
COMPARISON.append(j+'_'+i);
ANS_COUNT=ANS_COUNT+1;
答案 0 :(得分:6)
您应该使用itertools.combinations
:
>>> import itertools
>>> list(itertools.combinations([1,2,3,4,5,6], 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
答案 1 :(得分:0)
您也可以使用for循环执行此操作:
l = list()
for i in range (1,7):
for j in range (2,7):
if(i == j):
j = j + 1
elif ((i,j) in l or (j,i) in l):
continue
else:
l.append((i,j))
print l
输出:
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]