我有一个带有未指定编号的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
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
编辑:对代码进行了更改.这就是我想要做的.我想知道的是除了循环之外我还能使用什么.
似乎是一份工作 itertools.combinations
from itertools import combinations
for a, b in combinations(intList, 2):
print abs(a - b)
Run Code Online (Sandbox Code Playgroud)
如果你想:)你甚至可以把这个变成列表理解
[abs(a -b) for a, b in combinations(intList, 2)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1137 次 |
| 最近记录: |