我看过另一篇标题与此相关的文章,但我感到困惑,因为我的值已经是整数。我希望脚本查看每个键的值(具有多个值的数组),通过使其成为列表来对数组进行排序,然后迭代经过排序和转换后的列表的值,从第二个值中减去第一个,然后从第三个值中减去第二个,等等,将差异存储在列表中。
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__'
最佳答案
您尝试在__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]}
关于python - TypeError:对象没有属性“__getItem__”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41987618/