递增的一组数字之间的差的笨拙计算,有没有更漂亮的方法? [英] Clunky calculation of differences between an incrementing set of numbers, is there a more beautiful way?

查看:98
本文介绍了递增的一组数字之间的差的笨拙计算,有没有更漂亮的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以正常工作.但这似乎太冗长了,确定有一种更优雅的方法可以计算出来吗?

The following code works just fine. But it seems so verbose, surely there is a more elegant way to calculate this?

这个想法是我有一个100个递增时间戳的列表,我想查看这些时间戳并计算每个时间戳之间的平均时间.

The idea is that I have a list of 100 incrementing timestamps, I want to look at those timestamps and calculate the mean time between each time-stamp.

下面的代码起作用了,但是我确定反转这样的列表确实效率不高.

The code below functions, but I'm sure it's really inefficient to be reversing lists like this.

有什么建议吗?

#!/usr/bin/python 

nums = [1,4,6,10]
print nums
nums_orig = list(nums)

nums_orig.pop()
nums.reverse()
nums.pop()
nums.reverse()

print nums
print nums_orig

total = 0

for idx, val in enumerate(nums):
  difference = val - nums_orig[idx]
  total += difference
  print idx, val - nums_orig[idx]

print "Mean difference is %d" % (total / len(nums))

推荐答案

您正在寻找的是

>>> nums = [1,4,6,10]
>>> [x-y for x,y in zip(nums[1:],nums)]
[3, 2, 4]
>>> delta=[x-y for x,y in zip(nums[1:],nums)]
>>> float(sum(delta))/len(delta)
3.0

使用Starmap的解决方案

Solution with using Starmap

>>> from itertools import starmap
>>> from operator import sub
>>> sum(starmap(sub,zip(nums[1:],nums)))/float(len(nums)-1)
3.0

这篇关于递增的一组数字之间的差的笨拙计算,有没有更漂亮的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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