我看过另一篇有这个标题的帖子,但我很困惑,因为我的值已经是整数了。我希望脚本查看每个键的值(具有多个值的数组),通过将数组设为列表对数组进行排序,然后遍历排序和转换后的列表的值,从第二个中减去第一个,然后从第三个中减去第二个, 依此类推,将差异存储在列表中。
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__'
请您参考如下方法:
>>> 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])}
