【问题标题】:Python inverted index issue: "ValueError: too many values to unpack"Python 倒排索引问题:“ValueError: too many values to unpack”
【发布时间】:2014-08-06 16:04:13
【问题描述】:

我正在尝试建立一个倒排索引,但我仍然遇到同样的错误

ValueError:解包的值太多

它出现在我的这部分代码中:

def inverted_index(self, text):

    terms = self.getTerms(text)
    inverted = {}
    for index, word in terms:
            locations = inverted.setdefault(word)
            locations.append(index)

    return inverted

在“for inde, word in terms:”这一行更具体:

如果我打印术语,我会得到一个单词列表:

['12th', 'comput', 'olympiad', 'ciao', 'chiamo', 'alberto', 'lancellotti', 'scrivendo', 'primo', 'articolo', 'piccolo', 'motor', 'ricerca', 'manual']

有什么想法吗?

【问题讨论】:

    标签: python indexing unpack


    【解决方案1】:

    Python 抱怨是因为terms 的每次迭代只返回一件事——值。你想要的是

    for index, word in enumerate(terms):
    

    这将返回项目的索引和项目本身。

    【讨论】:

      【解决方案2】:
      for index, word in enumerate(terms)
      

      enumerate 会给你列表中每个项目的索引

      In [5]: for index, word in enumerate(terms):              
                  print(index,word)       
      (0, '12th')
      (1, 'comput')
      (2, 'olympiad')
      (3, 'ciao')
      (4, 'chiamo')
      (5, 'alberto')
      (6, 'lancellotti')
      (7, 'scrivendo')
      (8, 'primo')
      (9, 'articolo')
      (10, 'piccolo')
      (11, 'motor')
      (12, 'ricerca')
      (13, 'manual')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-19
        • 2019-02-01
        • 1970-01-01
        • 2016-11-05
        • 2014-03-31
        • 2020-04-01
        • 2020-09-23
        • 1970-01-01
        相关资源
        最近更新 更多