我正在尝试迭代map
(dictionary)中的所有元素。但我得到了这个错误。为什么它把dict
写成list
?我们如何解决这个问题呢?在
'list' object has no attribute 'items' on line 13 in main.py
def thirdfarthestdistance(arr,x):
map = {}
for elem in arr:
# Storing {(5, -3), (distance, element)}
map[abs(elem-x)] = elem
map = sorted(map)
count = 0
for key, value in map.items: # I tried map.items() too but didn't work.
print(value)
# if count == 2:
# return elem
count = count + 1
print(thirdfarthestdistance([-3, -2, -1, 4, 7], 2))
问题在于排序(…)方法。来自python文档:
https://docs.python.org/3/library/functions.html#sorted
您将看到该方法返回一个列表。因此,当你打电话
你实际上是在把你的字典转换成一个排序的列表。在
在我的头脑中,一个更好的方法是获得一个排序的键列表,然后引用它。有点像
^{pr2}$显然,这不包括对初始数组的验证。在
sorted
返回一个列表;您正在用排序键列表替换您的dict
。在相反,你只是想
它迭代按键排序的键/值对列表。在
相关问题 更多 >
编程相关推荐