Python 类型错误:“zip”对象不可下标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27431390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:47:45  来源:igfitidea点击:

TypeError: 'zip' object is not subscriptable

pythonpython-3.x

提问by sss

I have a tagged file in the format token/tag and I try a function that returns a tuple with words from a (word,tag) list.

我有一个 token/tag 格式的标记文件,我尝试了一个函数,该函数返回一个包含 (word,tag) 列表中的单词的元组。

def text_from_tagged_ngram(ngram): 
    if type(ngram) == tuple:
        return ngram[0]
    return " ".join(zip(*ngram)[0]) # zip(*ngram)[0] returns a tuple with words from a (word,tag) list

In python 2.7 it worked well, but in python 3.4 it gives me the following error:

在python 2.7中它运行良好,但在python 3.4中它给了我以下错误:

return " ".join(list[zip(*ngram)[0]])
TypeError: 'zip' object is not subscriptable

Can someone help?

有人可以帮忙吗?

采纳答案by khelwood

In Python 2, zipreturned a list. In Python 3, zipreturns an iterable object. But you can make it into a list just by calling list, as in:

在 Python 2 中,zip返回一个列表。在 Python 3 中,zip返回一个可迭代对象。但是你可以通过调用将它变成一个列表list,如下所示:

list(zip(...))

In this case, that would be:

在这种情况下,这将是:

list(zip(*ngram))

With a list, you can use indexing:

对于列表,您可以使用索引:

items = list(zip(*ngram))
...
items[0]

etc.

等等。

But if you only need the first element, then you don't strictly need a list. You could just use next.

但是如果你只需要第一个元素,那么你就不需要一个列表。你可以只使用next.

In this case, that would be:

在这种情况下,这将是:

next(zip(*ngram))