Python 统计字符串中每个单词的长度
我们将编写一个 Python 程序来统计字符串中每个单词的长度。这个程序将首先将字符串分割成单词列表,然后遍历每个单词并计算其长度。
实例
def word_lengths(s):
words = s.split()
lengths = [len(word) for word in words]
return dict(zip(words, lengths))
# 示例字符串
text = "Hello world this is a test"
result = word_lengths(text)
print(result)
words = s.split()
lengths = [len(word) for word in words]
return dict(zip(words, lengths))
# 示例字符串
text = "Hello world this is a test"
result = word_lengths(text)
print(result)
代码解析:
word_lengths(s)
函数接受一个字符串s
作为参数。s.split()
将字符串s
按空格分割成单词列表words
。[len(word) for word in words]
使用列表推导式遍历words
列表中的每个单词,并计算其长度,生成一个包含所有单词长度的列表lengths
。dict(zip(words, lengths))
将words
和lengths
两个列表组合成一个字典,其中键是单词,值是对应的长度。- 最后,函数返回这个字典。
输出结果:
实例
{'Hello': 5, 'world': 5, 'this': 4, 'is': 2, 'a': 1, 'test': 4}
点我分享笔记