将功能转换为理解

发布于 2025-01-31 20:10:02 字数 300 浏览 1 评论 0原文

我想将以下函数转换为简化的列表理解

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滥情哥ㄟ 2025-02-07 20:10:02

您可以通过使用发电机表达式使用sum更轻松地计数辅音数,而不是构建列表并使用其len。除此之外,要使此功能较短所需要做的就是摆脱中间变量声明,而只是打印列表。 返回 print均无意义,因为print()总是返回none无论如何。

def number_of_consonants(words):
    print([
        sum(letter not in 'aeiou' for letter in word.lower())
        for word in words.split()
    ])
>>> number_of_consonants("the quick brown fox")
[2, 3, 4, 2]

如果要返回列表而不是打印,只需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 its len. 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 in returning the print since print() always returns None anyway.

def number_of_consonants(words):
    print([
        sum(letter not in 'aeiou' for letter in word.lower())
        for word in words.split()
    ])
>>> number_of_consonants("the quick brown fox")
[2, 3, 4, 2]

If you wanted to return the list rather than printing it, just replace print([...]) with return [...].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文