我想在列表中的每对元素之间进行比较,而不是以下内容: 差异=[1,2,3,4,5,6]
- 没有 self 比较
- 没有反向比较
所以答案将是 [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;
最佳答案
你应该只使用 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)]
关于python 列表项组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22972223/