计算python列表中相邻项目之间的差异 [英] Calculate difference between adjacent items in a python list

查看:51
本文介绍了计算python列表中相邻项目之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数百万个号码的清单.我想找出排序列表中每个数字之间的差异是否与整个列表相同.

I have a list of millions of numbers. I want to find out if the difference between each number in the ordered list is the same for the entire list.

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

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

做到这一点的最佳方法是什么?

What's the best way to do this?

我的尝试:

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

推荐答案

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

The straight approach here is the best:

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

这篇关于计算python列表中相邻项目之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆