python - 有没有办法缩短多个 if 语句?

这是一个计算单词中所有元音的程序,程序的大部分是多个 if 语句,有什么办法可以缩短它吗?

word = input("enter a word ").lower()
a, e, i , o , u = 0, 0, 0, 0, 0
letters = [char for char in word]
for x in range(0,len(letters)):
    if letters[x] == "a":
        a += 1
    elif letters[x] == "e":
        e += 1
    elif letters[x] == "i":
        i += 1
    elif letters[x] == "o":
        o += 1
    elif  letters[x] == "u":
        u += 1
print(f"The word `{word}` has {a} `a` characters, {e} `e` characters, {i} `i` characters, {o} `o` characters, {u} `u` characters")

最佳答案

不要使用 5 个单独的变量,每个元音一个。使用带有元音键的单个 dict

vowels = "aeiou"
vowel_counts = { x: 0 for x in vowels }

for x in letters:
    if x in vowels:
        vowel_counts[x] += 1

print(f"The word `{word}` has {vowel_counts['a']} `a` characters, {vowel_counts['e']} `e` characters, {vowel_counts['i']} `i` characters, {vowel_counts['o']} `o` characters, {vowel_counts['u']} `u` characters")

https://stackoverflow.com/questions/67448102/

相关文章:

fortran - Fortran 中的嵌套名单

react-native - 部署 key 为空 appcenter 代码推送 cli

python - Python 中的 Hangman 游戏

python - 基于字典值映射Python列表

r - 将列中以冒号分隔的字符串拆分为 R 中的不同列

visual-studio-code - 删除 VSCode 中的 Sublime 文本主题

amazon-web-services - CloudFormation YAML - 带有条件语句

python - 将 VSCode 更新到 1.56.1 后,出现错误 : "Cannot acti

reactjs - 在@auth0 中 Jest 模拟 Auth0Client

c++ - 在 C++ 中定义类枚举值的 std::vector 的缩写语法