【发布时间】:2017-10-02 00:13:28
【问题描述】:
我正在编写此代码,该代码将页码映射到该页面上的单词并将其反转,以便创建一个新的有序字典,将每个唯一单词映射到该单词出现的所有页面
例如输入:
words_on_page = {1: ['hi', 'there', 'fred'], 2: ['there', 'we', 'go'], 3: ['fred', 'was', 'there']}
.....应该返回为:
{'hi':[1], 'fred':[1, 3], 'there': [1, 2, 3], 'we' :[2], 'go': [2], 'was': [3]}
到目前为止,我的解决方案是反转字典,但它使关键是该页面上的每个单词都映射到页码。我需要一些如何拆分键中的单词并将它们映射到它们出现的所有页面的列表
def make_index(words_on_page):
"""returnings inverse dictionarty mapping from a word (key) to an
ordered list of pages on which that word appears"""
inverted = {}
for page, word in words_on_page.items():
word = str(word)
if word in inverted:
inverted[word].append(page)
else:
inverted[word] = [page]
return inverted
【问题讨论】:
-
我想我已经弄清楚了,我只需要添加另一个迭代来遍历单词列表中的所有单词,例如:for page,words_on_page.items()中的单词:for word in words :""
标签: python list dictionary