我知道这可能是一个非常基本的问题,但我在 Python 上发现了一些奇怪的东西。我将尝试用以下示例来解释这一点:
l = [1,2,3,4,5]
n1 = 1
我们知道以下内容:
print( n1 in l ) # True # is n1 in the list l1?
print( not(n1 in l) ) # False # is n1 not in the list l1?
我可以使用:
print( (n1 in l) == True ) # True
# this will be like
# True == True
# True
我的问题是当我不使用括号时,例如:
print( n1 in l == True ) # False
这里控制台的答案是 False
我试图理解这其中的逻辑
所以如果我尝试一步一步去做
n1 in l == True
l == True # this is False, l es not a boolean True, it is a list
n1 in False # this is not False, actually if you run it it will be an error
print( n1 in False) # TypeError: argument of type 'bool' is not iterable
因此,为什么我跑步:
print( n1 in l == True )
控制台上的答案是False?
提前非常感谢。
print( n1 in l == True ) # True
与:
相同print( (n1 in l) == True ) # True
看起来
==
和 in
具有相同的优先级,因此建议使用括号。
没有任何意义,因为 in 应该只适用于文档中提到的类型,但这就是动态类型语言的乐趣:D
https://docs.python.org/3/reference/expressions.html#operator-precedence