首页 > 解决方案 > 多条件python

问题描述

我想做一个计算字符串中辅音的函数,所以我尝试这样做:

def vowel_count(foo):
  count = 0
  for i in foo:
    if not i == 'a' and i == 'e' and i ... and i == 'O' and i == 'U':
      count += 1
return count

但这非常丑陋和乏味,在更多条件下更是如此。有没有办法把它们放在一起?

标签: pythonif-statement

解决方案


您正在寻找not in运营商。

def vowel_count(foo):
    count = 0
    for i in foo.lower():
        if i not in 'aeiou':
            count += 1
    return count

或更简单地说:

def vowel_count(foo):
    return sum(i not in 'aeiou' for i in foo.lower())  # True == 1, False == 0

推荐阅读