Python:为什么这不起作用? (非序列迭代)
我有一本字典,每个键都包含一个列表作为值。我正在尝试检查列表中的所有项目,假设我正在尝试打印所有项目,我写道:
for item in aDict:
for item2 in aDict[item]:
print item2
这将打印列表中的第一个值的项目,然后它给我一个错误,说“迭代非序列”。这是为什么?我应该怎么做?
提前致谢。
I have a dictionary with each key containing a list as a value. And I'm trying to go over all the items in the lists, and let's say I'm trying to print all the items as I go through, I wrote:
for item in aDict:
for item2 in aDict[item]:
print item2
This prints out the items in the list for the first value, then it gives me an error saying "iteration over non-sequence". Why is this and how should I do this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的字典值之一不是列表!
One of your dictionary values is not a list!
我假设 aDict 中的一项不是 序列、字符串、列表、元组等:
I'm assuming one of the items in
aDict
is not a sequence, string, list, tuple etc:当你这样做时:
你的说法是,对于字典中的每个
item
,循环遍历字典中的item
索引,这没有任何意义。您真正想要做的是对于每个
item
,循环遍历该特定项目,例如:或使用更好的术语:
When you do this:
Your saying, for each
item
in the dictionary, loop through theitem
index in the dictionary, which doesn't make any sense.What you really want to do is for each
item
, loop through that specific item, like:or using better terms:
aDict[item]
意味着您想要字典的值,而不是键?在这种情况下,.itervalues()
或.iteritems()
应该比默认迭代(仅在键上)更自然。该错误指出(至少其中一个)您的值不可迭代。
aDict[item]
implies that you want the values of the dict, not the keys? In which case.itervalues()
or.iteritems()
should be more natural than the default iteration (over keys only).The error points to (at least one of) your values is not iterable.