繁体   English   中英

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

[英]Calculate difference between adjacent items in a python list

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

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

使用纯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的数组),如果你有数百万的数字,可能会吞噬你的可用内存。

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

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...

需要注意的是,该列表可能有数百万个数字。 理想情况下,除非必要,否则我们不应迭代整个列表。 我们还需要避免构造新的列表,这可能会占用大量内存。 使用all和一个发生器将解决问题

 >>> x = [5, 10, 15, 20, 25]
 >>> all(x[i] - x[i-1] == x[i+1] - x[i] for i in xrange(1, len(x) - 1))
 True

itertools.izip非常适合这种事情:

>>> lst = [1,1,2,3,5,8]
>>> [y-x for x, y in itertools.izip (lst, lst[1:])]
[0, 1, 1, 2, 3]

我在玩的时候来到这里:

>>> exm = [0,5,10,15,20,25,30,35]
>>> len(set(exm[a + 1] - exm[a] for a in range(0, len(exm) - 1))) == 1

我所做的是每对连续项确定它们在发电机中的差异。 然后我将所有这些差异添加到一个集合中以仅保留唯一值。 如果此集合的长度为1,则所有差异都相同。


编辑:查看cldy的答案 ,当发现任何项目与初始差异不同时,您可以提前停止执行:

>>> exm = [0,5,10,15,20,25,30,35]
>>> initial_diff = exm[1] - exm[0]
>>> difference_found = any((exm[a + 1] - exm[a]) != initial_diff 
                                for a in range(1, len(exm) - 1))
>>> x=[10,15,20,25]
>>> diff=(x[-1]-x[0])/(len(x)-1)
>>> diff
5
>>> all(x[i]+diff==x[i+1] for i in range(len(x)-1))
True

这是一个在numpy使用diff函数的例子。

例如

import numpy
numpy_array = numpy.zeros(10**6)
for i in xrange(10**6):
    numpy_array[i] = i
print numpy.any(numpy.diff(a) == 1)

真正

这是一个使用迭代器进行比较的解决方案..并且可能是不需要知道输入数据长度的优点; 你可能可以避免首先将数百万个列表项加载到内存中......

from itertools import tee, izip

# From itertools recipes: http://docs.python.org/library/itertools.html
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

class DifferenceError(Exception):
  pass

def difference_check(data):
  idata = pairwise(data)
  (a,b) = idata.next()
  delta = b - a
  for (a,b) in idata:
    if b - a != delta:
      raise DifferenceError("%s -> %s != %s" % (a,b,delta))
  return True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM