无法迭代python字典。(“list”对象在中的第13行没有属性“items”主.py)

2024-10-01 13:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试迭代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))

Tags: in元素mapfordictionaryvaluecount错误
2条回答

问题在于排序(…)方法。来自python文档:

https://docs.python.org/3/library/functions.html#sorted

您将看到该方法返回一个列表。因此,当你打电话

map = sorted(map)

你实际上是在把你的字典转换成一个排序的列表。在

在我的头脑中,一个更好的方法是获得一个排序的键列表,然后引用它。有点像

^{pr2}$

显然,这不包括对初始数组的验证。在

sorted返回一个列表;您正在用排序键列表替换您的dict。在

相反,你只是想

for key, value in sorted(map.items()):

它迭代按键排序的键/值对列表。在

相关问题 更多 >