python list item combinations
我想对列表中的每对元素进行比较,但不包括以下内容:差异=[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]到目前为止,我已经写了这篇文章,但我正在寻找一种更快的方法。
1 2 3 4 5 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; |
您只需使用
1 2 3 | >>> 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)] |
您也可以使用for循环执行此操作:
1 2 3 4 5 6 7 8 9 10 11 | 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 | [(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)] |