for x in y () : 어떻게 작동합니까?
이 질문에 이미 답변이 있습니다.
- "수익"키워드의 기능은 무엇입니까? 38 답변
터미널에서 커서를 돌리는 코드를 찾고 있었고 이것을 발견했습니다. 코드에서 무슨 일이 일어나고 있는지 궁금합니다. 특히 for c in spinning_cursor():
저는이 구문을 본 적이 없습니다. 을 사용하여 한 번에 생성기에서 하나의 요소를 반환하기 때문에 yield
이것이 c에 할당됩니까? y ()에서 x에 대한 다른 예가 있습니까?
import sys
import time
def spinning_cursor():
cursor='/-\|'
i = 0
while 1:
yield cursor[i]
i = (i + 1) % len(cursor)
for c in spinning_cursor():
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\b')
사용 yield
하면 함수가 생성기 로 바뀝니다 . 생성기는 특수한 유형의 반복자 입니다. for
항상 반복 가능한 항목을 반복하여 각 요소를 차례로 가져와 나열한 이름에 할당합니다.
spinning_cursor()
생성기를 반환하면 내부 코드 spinning_cursor()
는 생성기를 반복 할 때까지 실제로 실행되지 않습니다. 생성기를 반복한다는 것은 함수의 코드가 yield
명령문을 만날 때까지 실행된다는 것을 의미합니다. 이때 표현식의 결과가 다음 값으로 반환되고 실행이 다시 일시 중지됩니다.
for
루프는 동등한 전화 할게 그냥 것을하지 next()
가 제기하여 수행됩니다 발전기 신호 때까지 발전기에 StopIteration
(때 함수가 반환 일어나는). 의 각 반환 값은 next()
차례로에 할당됩니다 c
.
Python 프롬프트에서 생성기를 생성하여이를 확인할 수 있습니다.
>>> def spinning_cursor():
... cursor='/-\|'
... i = 0
... while 1:
... yield cursor[i]
... i = (i + 1) % len(cursor)
...
>>> sc = spinning_cursor()
>>> sc
<generator object spinning_cursor at 0x107a55eb0>
>>> next(sc)
'/'
>>> next(sc)
'-'
>>> next(sc)
'\\'
>>> next(sc)
'|'
이 특정 생성기는 반환 StopIteration
되지 않으므로 발생하지 않으며 for
스크립트를 종료하지 않는 한 루프가 영원히 계속됩니다.
훨씬 더 지루하지만 더 효율적인 대안은 다음을 사용하는 것입니다 itertools.cycle()
.
from itertools import cycle
spinning_cursor = cycle('/-\|')
Python에서 for 문을 사용하면 요소를 반복 할 수 있습니다.
문서 에 따르면 :
파이썬의 for 문은 시퀀스에 나타나는 순서대로 모든 시퀀스 (목록 또는 문자열)의 항목을 반복합니다.
여기서 요소는의 반환 값이 spinning_cursor()
됩니다.
for c in spinning_cursor()
문법 A는 for-each
루프. 에서 반환 한 반복기의 각 항목을 반복합니다 spinning_cursor()
.
루프 내부는 다음과 같습니다.
- 문자를 표준 출력에 쓰고 플러시하여 표시합니다.
- 10 분의 1 초 동안 자
- Write
\b
, which is interpreted as a backspace (deletes the last character). Notice this happens at the end of the loop so it won't be written during the first iteration, and that it shares the flush call in step 1.
spinning_cursor()
is going to return a generator, which doesn't actually run until you start iterating. It looks like it will loop through '/-\|'
, in order, forever. It's kind of like having an infinite list to iterate through.
So, the final output is going to be an ASCII spinner. You'll see these characters (in the same spot) repeating until you kill the script.
/
-
\
|
Martijn Pieters explanation is excellent. Below is another implementation of the same code you had in the question. it uses itertools.cycle to produce the same result as spinning_cursor
. itertools is filled with excellent examples of iterators and functions to help create your own iterators. It might help you understand iterators better.
import sys, time, itertools
for c in itertools.cycle('/-\|'):
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\b')
the spinning_cursor function returns an iterable (a generator from yield).
for c in spinning_cursor():
would be the same as
for i in [1, 2, 3, 4]:
참고URL : https://stackoverflow.com/questions/16483625/for-x-in-y-how-does-this-work
'Development Tip' 카테고리의 다른 글
MySQL 데이터베이스를 SQLite 데이터베이스로 내보내기 (0) | 2020.10.27 |
---|---|
RequireJS : 템플릿 및 CSS를 포함한 모듈로드 (0) | 2020.10.27 |
Gradle을 사용하여 Artifactory에 아티팩트 업로드 (0) | 2020.10.27 |
파이프 파손 오류의 원인은 무엇입니까? (0) | 2020.10.27 |
C #에서 인터페이스 기반 프로그래밍을 사용한 연산자 오버로딩 (0) | 2020.10.27 |