计算python列表中相邻项目之间的差异

新手上路,请多包涵

我有一个包含数百万个数字的列表。我想知道有序列表中每个数字之间的差异对于整个列表是否相同。

list_example = [ 0, 5, 10, 15, 20, 25, 30, 35, 40, ..等等等等]

最好的方法是什么?

我的尝试:

 import collections

list_example = [ 0, 5, 10, 15, 20, 25, 30, 35, 40 ]

count = collections.Counter()

for x,y in zip(list_example[0::],list_example[1::]):
    print x,y,y-x
    count[y-x] +=1

if len( count ) == 1:
    print 'Differences all the same'

结果:

 0 5 5
5 10 5
10 15 5
15 20 5
20 25 5
25 30 5
30 35 5
35 40 5
Differences all the same

原文由 Martlark 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 658
2 个回答

这里的直接方法是最好的:

 x = s[1] - s[0]
for i in range(2, len(s)):
    if s[i] - s[i-1] != x: break
else:
    #do some work here...

原文由 Mariy 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用纯 Python:

 >>> x = [0,5,10,15,20]
>>> xdiff = [x[n]-x[n-1] for n in range(1,len(x))]
>>> xdiff
[5, 5, 5, 5]
>>> all([xdiff[0] == xdiff[n] for n in range(1,len(xdiff))])
True

如果您使用 NumPy,它会更容易一些,而且可能更快:

 >>> import numpy as np
>>> xdiff = np.diff(x)
>>> np.all(xdiff[0] == xdiff)
True

但是这两者都会创建两个额外的列表(或数组,在 NumPy 的情况下),如果您有数百万个数字,它们可能会占用您的可用内存。

原文由 mtrw 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题