返回字符串中单词的字典长度

A.S*_*eec 7 python string dictionary

我需要构建一个函数,该函数将字符串作为输入并返回字典.
键是数字,值是包含具有等于键的字母数的唯一字的列表.
例如,如果输入函数如下:

n_letter_dictionary("The way you see people is the way you treat them and the Way you treat them is what they become")
Run Code Online (Sandbox Code Playgroud)

该函数应返回:

{2: ['is'], 3: ['and', 'see', 'the', 'way', 'you'], 4: ['them', 'they', 'what'], 5: ['treat'], 6: ['become', 'people']}
Run Code Online (Sandbox Code Playgroud)

我写的代码如下:

def n_letter_dictionary(my_string):
    my_string=my_string.lower().split()
    sample_dictionary={}
    for word in my_string:
        words=len(word)
        sample_dictionary[words]=word
    print(sample_dictionary)
    return sample_dictionary
Run Code Online (Sandbox Code Playgroud)

该函数返回字典如下:

{2: 'is', 3: 'you', 4: 'they', 5: 'treat', 6: 'become'}
Run Code Online (Sandbox Code Playgroud)

字典不包含具有相同字母数的所有单词,但仅返回字符串中的最后一个单词.

gtl*_*ert 7

由于您只想在lists中存储唯一值,因此使用a实际上更有意义set.你的代码几乎是正确的,你只需要确保你创建一个setif words不是你字典中的一个键,但你添加到setif words已经是你字典中的一个键.以下显示:

def n_letter_dictionary(my_string):
    my_string=my_string.lower().split()
    sample_dictionary={}
    for word in my_string:
        words=len(word)
        if words in sample_dictionary:
            sample_dictionary[words].add(word)
        else:
            sample_dictionary[words] = {word}
    print(sample_dictionary)
    return sample_dictionary

n_letter_dictionary("The way you see people is the way you treat them and the Way you treat them is what they become")
Run Code Online (Sandbox Code Playgroud)

产量

{2: set(['is']), 3: set(['and', 'the', 'see', 'you', 'way']), 
 4: set(['them', 'what', 'they']), 5: set(['treat']), 6: set(['become', 'people'])}
Run Code Online (Sandbox Code Playgroud)


ope*_*guy 0

my_string="a aa bb ccc a bb".lower().split()
sample_dictionary={}
for word in my_string:
    words=len(word)
    if words not in sample_dictionary:
        sample_dictionary[words] = []
    sample_dictionary[words].append(word)
print(sample_dictionary)
Run Code Online (Sandbox Code Playgroud)