gpt4 book ai didi

Python - 字典中的重复值

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:01 25 4
gpt4 key购买 nike

我写了下面的代码:

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'}
}

关于Python - 字典中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com