将功能转换为理解
我想将以下函数转换为简化的列表理解
def number_of_consonants(words):
words_split = words.split()
consonant_list = [len([letter for letter in word if letter.lower() not in 'aeiou']) \
for word in words_split]
return print(consonant_list)
该函数仅计算字符串中每个单词的辅音数
I would like to convert the following function into a simplified list comprehension
def number_of_consonants(words):
words_split = words.split()
consonant_list = [len([letter for letter in word if letter.lower() not in 'aeiou']) \
for word in words_split]
return print(consonant_list)
The function simply counts the number of consonants for each word in a string
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过使用发电机表达式使用
sum
更轻松地计数辅音数,而不是构建列表并使用其len
。除此之外,要使此功能较短所需要做的就是摆脱中间变量声明,而只是打印列表。返回
print
均无意义,因为print()
总是返回none
无论如何。如果要
返回
列表而不是打印,只需print> print([...])
return [...]
。You can count up the number of consonants more easily by using
sum
with a generator expression, rather than building a list and taking itslen
. Other than that, all you need to do to make this function shorter is get rid of the intermediate variable declarations and just print the list. There's no point inreturn
ing theprint
sinceprint()
always returnsNone
anyway.If you wanted to
return
the list rather than printing it, just replaceprint([...])
withreturn [...]
.