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")
推荐阅读
- android - 如何设置 Android Retrofit2 BASE URL 从活动中获取 EditText 的值?
- javafx - JavaFx一个接一个打印多个节点需要很长时间
- github - Xcode 10 github 推送坏了?
- reactjs - thunk 调度的正确 TypeScript 类型?
- asp.net - 处理开发时 web.config 冲突
- angular - 没有刷新令牌的 Ngx-auth
- makefile - 如何检测由于包含而导致的 Makefile 重新评估
- javascript - javascript - 重定向在 JSON 错误中给出了意外的令牌
- node.js - webpack / laravel mix 错误:Chunk.entrypoints:使用 Chunks.groupsIterable
- r - 基于两个数据集之间共享列的行绑定