【问题标题】:My iterator returns only keys not items upon printing我的迭代器在打印时只返回键而不是项目
【发布时间】:2018-06-15 03:45:33
【问题描述】:

我正在为字典实现我的自定义迭代器,但我得到的只是键而不是项目。我的代码是:

initial_song_data = {
"blue-da-ba-dee-sample.ogg": {
    "album": "Rush of Blood to the Head",
    "path": "blue-da-ba-dee-sample.ogg",
    "name": "blue da ba dee sample",
    "artists": ["Coldplay", "Nirvana"]
},
"to-bring-you-my-love.ogg": {
    "album": "Rush of Blood to the Head",
    "path": "to-bring-you-my-love.ogg",
    "name": "to bring you my love",
    "artists": ["Nirvana", "U2"]
}}

iter_obj = iter(initial_song_data)

while True:
    try:
        element = next(iter_obj)
        print(element.values())
    except StopIteration:
        break
for song in initial_song_data:
    print(song)

输出: blue-da-ba-dee-sample.ogg

to-bring-you-my-love.ogg

我在这里缺少什么?请帮忙。

【问题讨论】:

  • 您的代码在while True: 之后没有正确缩进请同时提供所需的输出。
  • 完成了,现在可以检查了吗?
  • 想要的输出?
  • 目的是什么?在 Python 中,通常不需要这样做。 while 循环很少使用。 for 循环可能更适合这种情况。

标签: python-3.x dictionary iterator


【解决方案1】:

iter 函数返回传递参数的迭代器对象。字典的迭代器遍历字典的键。这样就可以按预期工作了。

【讨论】:

    【解决方案2】:

    我不确定所需的输出,但如果您将 print(element.values()) 替换为 print(initial_song_data[element].values()) 可能会产生它? (或print(initial_song_data[element].items()),取决于你想得到什么)。

    顺便说一句,当我运行您的代码时(以交互方式使用 exec 内置函数),我得到了 AttributeError: 'str' object has no attribute 'values'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 2012-06-16
      • 2017-05-05
      • 2020-07-28
      • 1970-01-01
      • 2021-10-16
      • 2013-10-10
      相关资源
      最近更新 更多