【问题标题】:Question based on operator precedence in PythonPython中基于运算符优先级的问题
【发布时间】:2021-01-06 13:35:55
【问题描述】:
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' 的第一个字母Wi=0 的计算结果为False。因此,对于str 中的所有字母,除了i='e' 之外,我们有False not in i(不应该首先根据从左到右的顺序进行评估)相当于True。但是,python 解释器将 count 的值设为 3,这比我的逻辑应该得到的值要小得多。

谁能解释一下如何解决这个问题?这是我在 StackOverflow 上的第一个问题,如果我以错误的格式编写问题,我深表歉意。

谢谢。

【问题讨论】:

  • not in 应该做什么?
  • @Sayse 这就是我不明白的,我不明白“不在”的意思。但这是问题所在,它没有给出任何错误。
  • 由于您提到的运算符优先级,您正在评估((i=='e') not in i)=='l'not in 返回一个布尔值,它永远不会等于 'l'
  • @thshea 是的,但这是正确的优先级,对吧?所以我不明白我的逻辑有什么问题。
  • "所以,我们有 'False not in i' 这对于 str 中除 i='e' 之外的所有字母都等于 True" 但是然后您测试该结果是否等于 'l'。布尔值永远不会是。因此,该语句将始终评估为 false。

标签: python python-3.x operator-precedence


【解决方案1】:

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

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

【讨论】:

  • 但这是一个完全不同的问题,我知道如何解决这个元音问题。
  • 好吧,那么请忽略它。这就是为什么我说I will assume ....没问题。
猜你喜欢
  • 2021-07-20
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2011-10-19
相关资源
最近更新 更多