Python中基于运算符优先级的问题

问题描述

str = 'Welcome to the Jungle'
count = 0
for i in str:
    if i=='a' or i=='e' not in i=='l' or i=='o' or i=='u':
        count += 1
print(count)

使用 https://data-flair.training/blogs/python-operator-precedence/ 上给出的优先顺序,==not in 运算符具有相同的优先级,所以我必须从左到右。根据该逻辑,由于 i=='e' 对于第一个字母 i=0W 计算结果为 False。因此,对于 False not in i 中除 True 之外的所有字母,我们有 str(不应根据从左到右的顺序首先评估)它等于 i='e'。但是,python 解释器将 count 的值设为 3,这远小于我的逻辑应该得到的值。

有人可以解释一下如何解决这个问题吗?这是我在 StackOverflow 上的第一个问题,如果我的问题格式有误,我深表歉意。

谢谢。

解决方法

@SaumilSood - 你问过 how to solve this problem - 我假设你有兴趣以 Pythonic 的方式找出句子中有多少 vowels,如果是,你可以试试这个:>

s = 'Welcome to the Jungle'
>>> vowels = 'aeiou'
>>> sum(1 for c in s if c in vowels)
7

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...