我有一个未指定编号的 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
有一个更好的方法吗?
编辑:对代码进行了更改。这就是我想要做的。我想知道的是除了循环我还能用什么。