python - 在python中以句子的单词作为键,单词从1开始的位置数作为值构建字典
问题描述
我希望从下面的代码中得到这个输出:
{'Tell': 1, 'a': 2, 'little': 3, 'more': 4, 'about': 5, 'yourself': 6, 'as': 7, 'a': 8, 'developer': 9}
但我得到这个输出:
{'Tell': 1, 'a': 8, 'little': 3, 'more': 4, 'about': 5, 'yourself': 6, 'as': 7, 'developer': 9}
这是代码:
sentence = 'Tell a little more about yourself as a developer'
list_words = sentence.split()
d = {word: i for i, word in enumerate(list_words, 1)}
print(d)
你认为是什么问题?给出我想要的输出的代码是什么?
解决方案
您不能在字典中有两个相同的键,因此不可能在“a”出现两次的情况下获得预期的结果(一次用于“a”:2,再次用于“a”:8)。
您输出的数据结构可以是元组列表而不是字典:
r = [(word,i) for i,word in enumerate(list_words,1)]
[('Tell', 1), ('a', 2), ('little', 3), ('more', 4), ('about', 5),
('yourself', 6), ('as', 7), ('a', 8), ('developer', 9)]
或者,它可以是一个字典,其中包含每个单词的位置列表:
d = dict()
for i,word in enumerate(list_words,1):
d.setdefault(word,[]).append(i)
{'Tell': [1], 'a': [2, 8], 'little': [3], 'more': [4],
'about': [5], 'yourself': [6], 'as': [7], 'developer': [9]}
推荐阅读
- c# - 如何在 C# 中实现密钥库(证书)soapui?
- sql - 当字段不是数字时转换为数字
- mongodb - 查询文档及其嵌套数组
- servicestack - 在后端获取 json 大小写
- javascript - 在 CSS 中使用 Nativescript icomon 字体的颜色和大小
- android - 构建设备树以在 Rockchip rk3288 板上运行 Linux 内核
- batch-file - 在另一个文件 .bat 中删除具有其名称和路径的文件
- javascript - 将整个网页放入 document.write();
- c# - C#将数字插入到排序位置的列表框中
- python - Django 模型不适用于 Oracle 数据库