从列表Python中获取所有可能对的差异

时间:2013-09-19 23:18:21

标签: python list

我有一个带有未指定编号的int列表。我想找到列表中与某个值匹配的两个整数之间的区别。

#Example of a list
intList = [3, 6, 2, 7, 1]

#This is what I have done so far

diffList = []

i = 0
while (i < len(intList)):
    x = intList[i]

    j = i +1
    while (j < len(intList)):
        y = intList[j]

        diff = abs(x-y)
        diffList.append(diff)

        j += 1
    i +=1

#Find all pairs that has a difference of 2
diff = diffList.count(2)
print diff

有更好的方法吗?

编辑:对代码进行了更改。这就是我想要做的。我想知道的是除了循环之外我还能使用什么呢。

2 个答案:

答案 0 :(得分:7)

似乎是itertools.combinations

的工作
from itertools import combinations
for a, b in combinations(intList, 2):
   print abs(a - b)

如果你想要,你甚至可以把这个变成列表理解:)

[abs(a -b) for a, b in combinations(intList, 2)]

答案 1 :(得分:4)

int_list = [3, 6, 2, 7, 1]
for x in int_list:
    for y in int_list:
        print abs(x - y)