如何实现序号与单词正确关联?解决字典覆盖重复单词序号问题
问题说明
现有文件内容如下:
1 fire 2 water 3 fire 4 earth 5 light 6 light
需求是建立序号与单词的关联,查询序号1返回fire,查询序号3也返回fire。但当前代码创建的是单词到序号的字典,且因字典键的唯一性,同一单词只会保留最后一次出现的序号(比如fire仅对应3),同时完全不符合“用序号查单词”的需求:
with open(file, "r") as file: # Create a dictionary mapping each word to its corresponding number word_to_number = {word: int(num) for num, word in map(str.split, file)}
调整方案
根据实际需求分两种情况处理:
情况1:需要「序号→单词」的映射(用序号查单词)
这是最贴合需求的方案,直接调换字典的键值对,用序号(转为整数)作为键,单词作为值。因为每个序号唯一,不会出现覆盖问题:
with open(file, "r") as file: number_to_word = {int(num): word for num, word in map(str.split, file)}
使用示例:
number_to_word[1]返回firenumber_to_word[3]返回fire
情况2:需要「单词→多个序号」的映射(用单词查所有对应序号)
如果实际需求是通过单词查询所有匹配的序号,就把字典的值设为列表,收集同一单词的所有序号:
with open(file, "r") as file: word_to_numbers = {} for num, word in map(str.split, file): num_int = int(num) if word not in word_to_numbers: word_to_numbers[word] = [] word_to_numbers[word].append(num_int)
使用示例:
word_to_numbers["fire"]返回[1, 3]word_to_numbers["light"]返回[5, 6]
内容的提问来源于stack exchange,提问作者user3006593
相关产品推荐
相关产品推荐

