python计算单词长度_python – 返回字符串中的单词长度

参见英文答案 >

Adding more than one value to dictionary when looping through string                                    7个

我需要构建一个函数,该函数将字符串作为输入并返回字典.

键是数字,值是包含具有等于键的字母数的唯一字的列表.

例如,如果输入函数如下:

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

该函数应返回:

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

我写的代码如下:

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

该函数返回字典如下:

{2: 'is', 3: 'you', 4: 'they', 5: 'treat', 6: 'become'}

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值