使用split()方法获取sentence中的单词列表:
words = sentence.split()
然后使用enumerate 内置函数构造一个生成器,将升序数字与列表中的单词相关联。默认情况下,enumerate 从 0 开始编号,但您希望它从 1 开始,因此将该值作为第二个参数传递:
numbered_words = enumerate(words, 1)
然后使用dict 内置函数从该生成器的输出构造一个字典。幸运的是,生成器以与您尝试构建的格式匹配的格式发出其 (number, word) 元组——dict 通过使用元组中的第一项作为键,第二项作为值来构造字典:
sentence_dict = dict(numbered_words)
如果你想简洁,你可以把所有的东西都塞进一行:
sentence_dict = dict(enumerate(sentence.split(), 1))
enumerate 生成器是唯一棘手的部分。 enumerate 与xrange 相似,因为它不返回序列,而是返回一个可以从中提取序列的对象。为了演示那里发生了什么,您可以使用for 循环从enumerate 生成器中提取(数字,单词)对并打印它们:
for num, word in enumerate(['a', 'b', 'c', 'd'], 57):
print 'num is', num, 'and word is', word
这表明了这一点:
num is 57 and word is a
num is 58 and word is b
num is 59 and word is c
num is 60 and word is d