【问题标题】:How to simplify the IF statement in Python 3如何在 Python 3 中简化 IF 语句
【发布时间】:2016-09-03 16:01:07
【问题描述】:

我的 IF 语句如下:

...
if word.endswith('a') or word.endswith('e') or word.endswith('i') or word.endswith('o') or word.endswith('u'):
...

在这里,我必须使用 4 个 OR 来涵盖所有情况。无论如何我可以简化这个吗?我正在使用 Python 3.4。

【问题讨论】:

标签: python


【解决方案1】:

使用any

>>> word = 'fa'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>> word = 'fe'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>> 

【讨论】:

  • 就像在某人的回答中一样,您也可以使用"aeiou" 而不是列表['a', 'e'],因为列表和字符串在python 中都是可迭代的
【解决方案2】:

试试

if word[-1] in ['a','e','i','o','u']:

word[-1] 是最后一个字母

【讨论】:

    【解决方案3】:

    简单地说:

    >>> "apple"[-1] in 'aeiou'
    True
    >>> "boy"[-1] in 'aeiou'
    False
    

    【讨论】:

      【解决方案4】:

      word.endswith(c)word[-1] == c 相同,所以:

      VOWELS = 'aeiou'
      
      if word[-1] in VOWELS:
          print('{} ends with a vowel'.format(word)
      

      会的。无需构造列表、元组、集合或其他数据结构:只需测试字符串中的成员资格,在本例中为 VOWELS

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 2021-11-20
        • 2014-06-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-07
        • 1970-01-01
        • 2015-09-12
        相关资源
        最近更新 更多