【问题标题】:Is there a way to shorten multiple if statements?有没有办法缩短多个 if 语句?
【发布时间】:2021-07-30 12:55:28
【问题描述】:

这是一个计算一个单词中所有元音的程序,大部分程序是多个 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")

【问题讨论】:

标签: python


【解决方案1】:

不要使用 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")

【讨论】:

  • 然后使用为此构建的 Counter 类:Counter(letters) 将整理所有字母的计数,Counter(l for l in letters where l in vowels) 将仅计算元音(并且由于执行筛选)。无论哪种方式,这段代码都会有问题,因为它没有考虑变音符号,例如résumé 可能代表也可能不代表两个 e,具体取决于输入文本的 normalization
  • 这其实是最好的办法。 :D
猜你喜欢
  • 1970-01-01
  • 2020-11-17
  • 2019-12-23
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多