我有一个看起来像这样的字典(为了清晰起见空白):
dic={'848613': [-0.22307240991541583, -0.46447953845401646, -0.1864029726690461,
-0.17906908521977213, -0.22246125262797634, -0.09472937955312179,
-0.2884662396714418, -0.3703613161883342],
'820434': [-0.09142433555202074, -0.15535959723873796, -0.1402251633128967,
-0.2680956866863311, -0.2226923849088073, -0.28353898661065896,
-0.1501088752644665, -0.17976001111917592],
'846353': [0.12422057244522786, 0.1500662052036628, 0.15781989503119326,
0.176881049190539, 0.17090424661515094, 0.13956641689554858,
0.11129775606601039, 0.0794753207321874]}
我想计算同一个键中两个值之间的差异,例如,前两个值之间的差值为0.241407128539。我到目前为止使用的代码是:
x=[]
z=[]
l=0
for a in dic:
x.append(dic[a])
y=list(itertools.chain.from_iterable(x))
a=0
b=1
d=len(y)-1
for c in range(d):
z.append(y[a]-y[b])
a+=1
b+=1
print z
但是,当使用一个键的所有值并将它们与下一个键组合时,此代码将继续。这样它还可以计算键的最后一个值和下一个键的第一个值之间的差值。 有没有一种很好的方法可以解决这个问题,还是我必须删除所有错误的数字?
答案 0 :(得分:0)
您的代码非常复杂。如果要减去每个列表的前两个值,则直接循环遍历字典项:
for key, values in dic.iteritems():
print key, values[0] - values[1]
演示:
>>> dic={'848613': [-0.22307240991541583, -0.46447953845401646, -0.1864029726690461,
... -0.17906908521977213, -0.22246125262797634, -0.09472937955312179,
... -0.2884662396714418, -0.3703613161883342],
... '820434': [-0.09142433555202074, -0.15535959723873796, -0.1402251633128967,
... -0.2680956866863311, -0.2226923849088073, -0.28353898661065896,
... -0.1501088752644665, -0.17976001111917592],
... '846353': [0.12422057244522786, 0.1500662052036628, 0.15781989503119326,
... 0.176881049190539, 0.17090424661515094, 0.13956641689554858,
... 0.11129775606601039, 0.0794753207321874]}
>>>
>>> for key, values in dic.iteritems():
... print key, values[0] - values[1]
...
848613 0.241407128539
820434 0.0639352616867
846353 -0.0258456327584