多条件python

Hei*_*erg 2 python if-statement

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

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
Run Code Online (Sandbox Code Playgroud)

但这样做非常难看和繁琐,更多的条件更多.有没有办法将它们组合在一起?

che*_*ner 5

您正在寻找not in运营商.

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

或更简单地说:

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