2

我有一个未指定编号的 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

有一个更好的方法吗?

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

4

2 回答 2

10

似乎是一份工作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)]
于 2013-09-19T23:21:47.730 回答
4
int_list = [3, 6, 2, 7, 1]
for x in int_list:
    for y in int_list:
        print abs(x - y)
于 2013-09-19T23:21:34.070 回答