gpt4 book ai didi

python - 笨拙地计算一组递增的数字之间的差异,有没有更漂亮的方法?

转载 作者:行者123 更新时间:2023-11-28 19:33:35 26 4
gpt4 key购买 nike

下面的代码工作得很好。但这看起来很冗长,一定有更优雅的计算方法吗?

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

下面的代码可以运行,但我敢肯定像这样反转列表效率很低。

有什么建议吗?

#!/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))

最佳答案

如果你有 numpy:

>>> import numpy as np
>>> np.diff([1,4,6,10]).mean()
3.0

关于python - 笨拙地计算一组递增的数字之间的差异,有没有更漂亮的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10448122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com