小编A.S*_*eec的帖子

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

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

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)

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

python string dictionary

7
推荐指数
2
解决办法
4037
查看次数

标签 统计

dictionary ×1

python ×1

string ×1