gpt4 book ai didi

python - 返回一个唯一的单词字典,其键是数字,其值是等长单词的列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:41 25 4
gpt4 key购买 nike

我编写了一个函数 n_letter_dictionary(my_string) 来获取一个字典,其键是数字,其值是包含唯一单词的列表。这里单词的字母数等于键。这是我的代码:

def n_letter_dictionary(my_string):
my_string = my_string.lower().split()

L= []
for key in my_string:
if len(key) >1:
l={len(key):[key]}
L.append(l)
L.sort()
return L
s="The way you see people is the way you treat them and the Way you treat them is what they become"
print(n_letter_dictionary(s))

正确的输出应该是:

{2: ['is'], 3: ['and', 'see', 'the', 'way', 'you'], 4: ['them', 'they', 'what'], 5: ['treat'], 6: ['become', 'people']}

而我的代码给出以下输出:

[{2: ['is']}, {2: ['is']}, {3: ['and']}, {3:['see']},{3:['the']},{3:['the']},{3:['the']}, {3:['way']}, {3:['way']},{3:['way']},{3:['you']}, {3:['you']},{3:['you']}, {4:['them']}, {4:['them']}, {4:['they']},{4:['what']},{5: ['treat']},{5: ['treat']},{ 6:['become']}, {6:['people']}]

如何获得正确的输出?

最佳答案

您可以使用 defaultdict它可用于自动为每个条目设置集合,如下所示。这将确保只存储唯一的条目:

from collections import defaultdict

def n_letter_dictionary(my_string):
words = my_string.lower().split()
lengths = defaultdict(set)

for key in words:
if len(key) > 1:
lengths[len(key)].add(key)

return {key : sorted(value) for key, value in lengths.items()}

s = "The way you see people is the way you treat them and the Way you treat them is what they become"
lengths = n_letter_dictionary(s)

for key in sorted(lengths.keys()):
print(key, lengths[key])

请注意,您无法对字典进行排序,但可以以排序后的方式显示内容:

2 ['is']
3 ['and', 'see', 'the', 'way', 'you']
4 ['them', 'they', 'what']
5 ['treat']
6 ['become', 'people']

关于python - 返回一个唯一的单词字典,其键是数字,其值是等长单词的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35980844/

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