Python:为什么这不起作用? (非序列迭代)

发布于 2024-12-19 19:04:16 字数 230 浏览 0 评论 0原文

我有一本字典,每个键都包含一个列表作为值。我正在尝试检查列表中的所有项目,假设我正在尝试打印所有项目,我写道:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

書生途 2024-12-26 19:04:16

您的字典值之一不是列表!

One of your dictionary values is not a list!

乖乖兔^ω^ 2024-12-26 19:04:16

我假设 aDict 中的一项不是 序列、字符串、列表、元组等:

>>> aDict = { 'a' : [1, 2, 3,], 'b' : [4, 5, 6,], 'c' : [7, 8, 9,] }
>>> for item in aDict:
...     for item2 in aDict[item]:
...         print item2
...
1
2
3
7
8
9
4
5
6
>>>

I'm assuming one of the items in aDict is not a sequence, string, list, tuple etc:

>>> aDict = { 'a' : [1, 2, 3,], 'b' : [4, 5, 6,], 'c' : [7, 8, 9,] }
>>> for item in aDict:
...     for item2 in aDict[item]:
...         print item2
...
1
2
3
7
8
9
4
5
6
>>>
简单 2024-12-26 19:04:16

当你这样做时:

for item in aDict: 
    for item2 in aDict[item]: 
        print item2

你的说法是,对于字典中的每个 item ,循环遍历字典中的 item 索引,这没有任何意义。

您真正想要做的是对于每个 item,循环遍历该特定项目,例如:

for item in aDict: 
    for item2 in item: 
        print item2

或使用更好的术语:

for dictIndex in aDict: 
        for item in dictIndex: 
            print item

When you do this:

for item in aDict: 
    for item2 in aDict[item]: 
        print item2

Your saying, for each item in the dictionary, loop through the item 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:

for item in aDict: 
    for item2 in item: 
        print item2

or using better terms:

for dictIndex in aDict: 
        for item in dictIndex: 
            print item
拔了角的鹿 2024-12-26 19:04:16

aDict[item] 意味着您想要字典的值,而不是键?在这种情况下, .itervalues().iteritems() 应该比默认迭代(仅在键上)更自然。

for key, value in aDict.iteritems():
    for subvalue in value:
        pass

该错误指出(至少其中一个)您的值不可迭代。

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).

for key, value in aDict.iteritems():
    for subvalue in value:
        pass

The error points to (at least one of) your values is not iterable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文