TypeError:“ zip”对象不可下标


76

我有一个标记文件/标记格式的标记文件,并且尝试了一个函数,该函数返回一个带有(单词,标签)列表中单词的元组。

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

有人可以帮忙吗?


1
nelsonslog.wordpress.com/2015/04/20/python3-zip-is-a-hassle提供了您可能感兴趣的解决方法
。– jaggi

Answers:


135

在Python 2中,zip返回了一个列表。在Python 3中,zip返回一个可迭代的对象。但是您只需调用即可将其放入列表list,如:

list(zip(...))

在这种情况下,将是:

list(zip(*ngram))

通过列表,您可以使用索引:

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

等等

但是,如果只需要第一个元素,那么就不必严格要求列表了。您可以使用next

在这种情况下,将是:

next(zip(*ngram))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.