Skip to main content
 首页 » 编程设计

Python之字典中的重复值

2025年05月04日15mfrbuaa

我写了下面的代码:

def word_len_dict(text): 
    the_dict = {} 
    user_input = str(text) 
    words_list = user_input.split() 
    for word in words_list: 
        if len(word) in the_dict: 
            the_dict[len(word)] += [word] 
        else: 
            the_dict[len(word)] = [word] 
    return the_dict 

正文是:

"the faith that he had had had had an affect on his life" 

我的输出结果如下:

2 - ['an', 'he', 'on'] 
3 - ['had', 'had', 'had', 'had', 'his', 'the'] 
4 - ['life', 'that'] 
5 - ['faith'] 
6 - ['affect'] 

我希望我的输出是:

2 - ['an', 'he', 'on'] 
3 - ['had', 'his', 'the'] 
4 - ['life', 'that'] 
5 - ['faith'] 
6 - ['affect'] 

将其添加到字典时,如何阻止它重复值?

请您参考如下方法:

from collections import defaultdict 
 
def word_len_dict(text): 
    words_by_len = defaultdict(set) 
    for word in text.split(): 
        words_by_len[len(word)].add(word) 
    return words_by_len 
 
text = "the faith that he had had had had an affect on his life" 
word_len_dict(text) 

给予

{ 
    2: {'an', 'he', 'on'}, 
    3: {'had', 'his', 'the'}, 
    4: {'life', 'that'}, 
    5: {'faith'}, 
    6: {'affect'} 
}