如何计算字典中的值之间的差异

时间:2019-04-21 09:57:39

标签: python-3.x

我有一本这样的字典

time = {"0": 1552644000109, 
"1": 1552644000113, 
"2": 1552644000116, 
"3": 1552644000116, 
"4": 1552644000118, 
"5": 1552644000119, 
"6": 1552644000119, 
"7": 1552644000120, 
"8": 1552644000121, 
"9": 1552644000122, 
"10": 1552644000123, 
"11": 1552644000123, 
"12": 1552644000124}

我正在尝试计算0-1与1-2和2-3之间的差,依此类推..以便编写另一个if the difference is > x; do this

的代码。

这是我的代码:

I converted the keys into integer 

inttime = {int(k):int(v) for k,v in time.items()}
for k,v in inttime.items():
        a=  inttime[k+1][0]-inttime[k][0]
        print(a)

这是我的错误:

TypeError: 'int' object is not subscriptable

1 个答案:

答案 0 :(得分:0)

解决问题的一种简单方法是,当列表中的一个稍微移动时,将值列表压缩在一起。因此:

>>> values = list(time.values())
>>> shifted = values[1:]
>>> differences = [next_val - current for current, next_val in zip(values, shifted)]

>>> differences
[4, 3, 0, 2, 1, 0, 1, 1, 1, 1, 0, 1]