TypeError: ‘ zip’对象不可下标

我有一个标记文件的格式令牌/标记,并尝试使用一个函数返回一个元组,其中包含来自(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

在 python 2.7中,它工作得很好,但是在 python 3.4中,它给出了以下错误:

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

有人能帮忙吗?

84051 次浏览

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

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.

In this case, that would be:

next(zip(*ngram))