왜 파이썬에서 0, 0 == (0, 0)이 (0, False)
Python에서 (Python 3.6으로 만 확인했지만 이전 버전의 많은 버전도 유지해야한다고 생각합니다.)
(0, 0) == 0, 0 # results in a two element tuple: (False, 0)
0, 0 == (0, 0) # results in a two element tuple: (0, False)
(0, 0) == (0, 0) # results in a boolean True
그러나:
a = 0, 0
b = (0, 0)
a == b # results in a boolean True
두 접근 방식간에 결과가 다른 이유는 무엇입니까? 항등 연산자는 튜플을 다르게 처리합니까?
처음 두 표현식은 모두 튜플로 구문 분석합니다.
(0, 0) == 0
(False
) 다음에0
0
, 뒤에0 == (0, 0)
(여전히False
그런 식입니다).
식은 등식 연산자와 비교하여 쉼표 구분 기호의 상대적 우선 순위로 인해 그 방식으로 나뉩니다. Python은 두 개의식이 포함 된 튜플을 봅니다. 그 중 하나는 두 튜플 간의 동등성 테스트 대신에 동등성 테스트입니다.
그러나 세 번째 예에서는 튜플이 될 a = 0, 0
수 없습니다 . 튜플은 값의 모음이며, 동등성 테스트와 달리 할당은 파이썬에서 가치가 없습니다. 과제는 표현이 아니라 진술입니다. 튜플이나 다른 주변 표현에 포함될 수있는 값이 없습니다. (a = 0), 0
튜플로 해석을 강제하기 위해 같은 것을 시도 하면 구문 오류가 발생합니다. 따라서 변수에 대한 튜플 할당은 변수 a = (0, 0)
의 유일한 유효한 해석으로서 변수를 작성하여보다 명확하게 만들 수 있습니다 a = 0, 0
.
세 가지 경우 모두에서 볼 수있는 것은 언어 의 문법 사양 과 소스 코드에서 발생하는 토큰을 구문 분석하여 구문 분석 트리를 생성하는 방식의 결과입니다.
이 저수준 코드를 살펴보면 후드에서 발생하는 상황을 이해하는 데 도움이됩니다. 이 python 문을 가져 와서 바이트 코드로 변환 한 다음 dis
모듈을 사용하여 디 컴파일 할 수 있습니다 .
사례 1 : (0, 0) == 0, 0
>>> dis.dis(compile("(0, 0) == 0, 0", '', 'exec'))
1 0 LOAD_CONST 2 ((0, 0))
3 LOAD_CONST 0 (0)
6 COMPARE_OP 2 (==)
9 LOAD_CONST 0 (0)
12 BUILD_TUPLE 2
15 POP_TOP
16 LOAD_CONST 1 (None)
19 RETURN_VALUE
(0, 0)
먼저 first와 비교하여로 0
평가됩니다 False
. 그런 다음이 결과로 튜플을 구성하고 마지막으로 0
얻을 수 (False, 0)
있습니다.
사례 2 : 0, 0 == (0, 0)
>>> dis.dis(compile("0, 0 == (0, 0)", '', 'exec'))
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 0 (0)
6 LOAD_CONST 2 ((0, 0))
9 COMPARE_OP 2 (==)
12 BUILD_TUPLE 2
15 POP_TOP
16 LOAD_CONST 1 (None)
19 RETURN_VALUE
튜플은 0
첫 번째 요소로 구성됩니다. 두 번째 요소의 경우 첫 번째 경우와 동일한 검사가 수행되고로 평가되므로을 False
얻습니다 (0, False)
.
사례 3 : (0, 0) == (0, 0)
>>> dis.dis(compile("(0, 0) == (0, 0)", '', 'exec'))
1 0 LOAD_CONST 2 ((0, 0))
3 LOAD_CONST 3 ((0, 0))
6 COMPARE_OP 2 (==)
9 POP_TOP
10 LOAD_CONST 1 (None)
13 RETURN_VALUE
보시 (0, 0)
다시피, 이 두 튜플을 비교 하고 돌아 오는 것 True
입니다.
문제를 설명하는 또 다른 방법 : 사전 리터럴에 익숙 할 것입니다.
{ "a": 1, "b": 2, "c": 3 }
배열 리터럴
[ "a", "b", "c" ]
튜플 리터럴
( 1, 2, 3 )
but what you don't realize is that, unlike dictionary and array literals, the parentheses you usually see around a tuple literal are not part of the literal syntax. The literal syntax for tuples is just a sequence of expressions separated by commas:
1, 2, 3
(an "exprlist" in the language of the formal grammar for Python).
Now, what do you expect the array literal
[ 0, 0 == (0, 0) ]
to evaluate to? That probably looks a lot more like it should be the same as
[ 0, (0 == (0, 0)) ]
which of course evaluates to [0, False]
. Similarly, with an explicitly parenthesized tuple literal
( 0, 0 == (0, 0) )
it's not surprising to get (0, False)
. But the parentheses are optional;
0, 0 == (0, 0)
is the same thing. And that's why you get (0, False)
.
If you're wondering why the parentheses around a tuple literal are optional, it is largely because it would be annoying to have to write destructuring assignments that way:
(a, b) = (c, d) # meh
a, b = c, d # better
Adding a couple of parentheses around the order in which actions are performed might help you understand the results better:
# Build two element tuple comprising of
# (0, 0) == 0 result and 0
>>> ((0, 0) == 0), 0
(False, 0)
# Build two element tuple comprising of
# 0 and result of (0, 0) == 0
>>> 0, (0 == (0, 0))
(0, False)
# Create two tuples with elements (0, 0)
# and compare them
>>> (0, 0) == (0, 0)
True
The comma is used to to separate expressions (using parentheses we can force different behavior, of course). When viewing the snippets you listed, the comma ,
will separate it and define what expressions will get evaluated:
(0, 0) == 0 , 0
#-----------|------
expr 1 expr2
The tuple (0, 0)
can also be broken down in a similar way. The comma separates two expressions comprising of the literals 0
.
In the first one Python is making a tuple of two things:
- The expression
(0, 0) == 0
, which evaluates toFalse
- The constant
0
In the second one it's the other way around.
look at this example:
r = [1,0,1,0,1,1,0,0,0,1]
print(r==0,0,r,1,0)
print(r==r,0,1,0,1,0)
then result:
False 0 [1, 0, 1, 0, 1, 1, 0, 0, 0, 1] 1 0
True 0 1 0 1 0
then comparison just does to the first number(0 and r) in the example.
참고URL : https://stackoverflow.com/questions/44864156/why-in-python-does-0-0-0-0-equal-0-false
'Programming' 카테고리의 다른 글
Java에서 파일 크기를 얻는 방법 (0) | 2020.07.19 |
---|---|
C ++ 열거 형을 문자열로 변환하는 간단한 방법이 있습니까? (0) | 2020.07.19 |
jQuery에서 버튼 클릭 이벤트를 처리하는 방법은 무엇입니까? (0) | 2020.07.19 |
Android에서 JSON을 구문 분석하는 방법 (0) | 2020.07.18 |
git가“당신이 의미 한”제안을 어떻게 할 수 있습니까? (0) | 2020.07.18 |