【发布时间】: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
我的 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
使用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 中都是可迭代的
试试
if word[-1] in ['a','e','i','o','u']:
word[-1] 是最后一个字母
【讨论】:
简单地说:
>>> "apple"[-1] in 'aeiou'
True
>>> "boy"[-1] in 'aeiou'
False
【讨论】:
word.endswith(c) 与word[-1] == c 相同,所以:
VOWELS = 'aeiou'
if word[-1] in VOWELS:
print('{} ends with a vowel'.format(word)
会的。无需构造列表、元组、集合或其他数据结构:只需测试字符串中的成员资格,在本例中为 VOWELS。
【讨论】: