UFO ET IT

파이썬은 if의 조건을 느리게 평가합니까?

ufoet 2020. 12. 15. 19:35
반응형

파이썬은 if의 조건을 느리게 평가합니까?


예를 들어, 다음 진술이있는 경우 :

if( foo1 or foo2)
    ...
    ...

foo1이 참이면 파이썬은 foo2의 조건을 확인합니까?


예, Python은 부울 조건을 느리게 평가합니다.

문서는 말한다 ,

표현식 x와 y는 먼저 x를 평가합니다. x가 거짓이면 그 값이 반환됩니다. 그렇지 않으면 y가 평가되고 결과 값이 반환됩니다.

표현식 x 또는 y는 먼저 x를 평가합니다. x가 참이면 그 값이 반환됩니다. 그렇지 않으면 y가 평가되고 결과 값이 반환됩니다.


and or 게으르다

& | 게으르지 않다


파이썬의 게으름은 다음 코드로 증명할 수 있습니다.

def foo():
    print('foo')
    return False

def bar():
    print('bar')
    return False

foo() and bar()         #Only 'foo' is printed

반면에

foo() or bar()

'foo'와 'bar'가 모두 인쇄됩니다.


이것은 기술적으로 게으른 평가가 아니라 단락 부울 표현식입니다.

게으른 평가는 다소 다른 의미를 가지고 있습니다. 예를 들어, 진정한 게으른 평가는

def foo(arg) :
    print "Couldn't care less"

foo([][0])

하지만 파이썬은 그렇지 않습니다.

파이썬은 부울 인자라는 점에서 "echos"라는 점에서도 좋습니다. 예를 들어 또는 조건은 첫 번째 "진정한"인수 또는 마지막 인수 (모든 인수가 "거짓"인 경우)를 반환합니다. 및 조건은 그 반대입니다.

따라서 "에코 인수"부울은

2 및 [] 및 1

[]로 평가되고

[] 또는 1 또는 2

1로 평가


예, Python은 느리게 평가되므로 foo2확인되지 않습니다.

키가 존재하는지 모르는 경우 사전과 같은 객체에서 항목을 가져 오는 데 항상 이것을 사용합니다.

if 'key' in mydict and mydict['key'] == 'heyyo!':
    do_stuff()

자세한 설명은 @unutbu의 답변을 참조하십시오.


실제로 or단락 된 부분입니다.

>>> 1 or 1/0  #also 0 and 1/0
1
>>> 0 or 1/0  #also 1 and 1/0

Traceback (most recent call last):
  File "<pyshell#1240>", line 1, in <module>
    0 or 1/0
ZeroDivisionError: integer division or modulo by zero

A short demo would be to compare the time difference between

all(xrange(1,1000000000))

and

any(xrange(1,1000000000))

The all() has to check every single value, whilst the any() can give up after the first True has been found. The xrange, being a generator, therefore also gives up generating things as soon as the evaluator is done. For this reason, the all will consume large amounts of RAM and take ages, whilst the any will use just a few bytes and return instantaneously.

ReferenceURL : https://stackoverflow.com/questions/13960657/does-python-evaluate-ifs-conditions-lazily

반응형