我看过这个标题的另一篇文章,但我感到困惑,因为我的价值已经是整数。我希望脚本查看每个键的值(一个具有多个值的数组),通过将数组作为一个列表对数组进行排序,然后遍历排序和转换后的列表的值,从中减去第一个值。第二个,然后是第三个,依此类推,将差异存储在列表中。
b = {"a":[5,2,1],"b":[8,4,3]}
for k in b.values():
eVals = []
#print listVals
x = 0
for i in sorted(k):
dif = i[x+1] - i[x]
print dif
eVals.append(dif)
x +=1
这是错误:
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 323, in RunScript
debugger.run(codeObject, __main__.__dict__, start_stepping=0)
File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run
_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 654, in run
exec cmd in globals, locals
File "N:\Python\test_dict.py", line 1, in <module>
b = {"a":[5,2,1],"b":[8,4,3]}
TypeError: 'int' object has no attribute '__getitem__'
答案 0 :(得分:2)
>>> b = {"a":[5,2,1],"b":[8,4,3]}
>>> for key, value in b.iteritems():
... value.sort()
... value[:] = [cur-prev for cur, prev in zip(value, [0] + value[:-1])]
...
>>> b
{'a': [1, 1, 3], 'b': [3, 1, 4]}
如果你方便地使用numpy,你可以单线理解:
>>> import numpy as np
>>> b = {"a":[5,2,1],"b":[8,4,3]}
>>> {k: np.diff([0] + sorted(v)) for k, v in b.iteritems()}
{'a': array([1, 1, 3]), 'b': array([3, 1, 4])}
答案 1 :(得分:-1)
您尝试在__getitem__
上使用int
。
这是一个可能的解决方案
inp = {"a":[5,2,1],"b":[8,4,3]}
out = {}
for key, lis in inp.iteritems():
difLis = []
sLis = sorted(lis)
for i, _ in enumerate(sLis[:-1]):
dif = sLis[i+1] - sLis[i]
print "%d - %d = %d" % (sLis[i+1], sLis[i], dif)
difLis.append(dif)
out[key] = difLis
print out # {'a': [1, 3], 'b': [1, 4]}