반응형
enumerate () -Python에서 생성기 생성
생성기 함수의 결과를 열거 할 때 어떤 일이 발생하는지 알고 싶습니다. 예 :
def veryBigHello():
i = 0
while i < 10000000:
i += 1
yield "hello"
numbered = enumerate(veryBigHello())
for i, word in numbered:
print i, word
열거 형이 느리게 반복, 아니면 모든 것을 첫 번째로 말하는 것이 있습니까? 나는 그것이 게으른보고 99.999 % 확신한다. 그래서 그것을 생성기 함수와 똑같이 취급 할 수 있는가, 아니면 무엇을 조심해야 하는가?
게으르다. 그 사실을 증명하는 것이 매우 뛰어납니다.
>>> def abc():
... letters = ['a','b','c']
... for letter in letters:
... print letter
... yield letter
...
>>> numbered = enumerate(abc())
>>> for i, word in numbered:
... print i, word
...
a
0 a
b
1 b
c
2 c
이전 제안 중 하나보다 쉽게 알 수 있습니다.
$ python
Python 2.5.5 (r255:77872, Mar 15 2010, 00:43:13)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> abc = (letter for letter in 'abc')
>>> abc
<generator object at 0x7ff29d8c>
>>> numbered = enumerate(abc)
>>> numbered
<enumerate object at 0x7ff29e2c>
열거가 지연 평가를 수행하지 반환 [(0,'a'), (1,'b'), (2,'c')]
하거나 거의 (거의) 동등합니다.
물론 열거는 정말 멋진 생성기 일뿐입니다.
def myenumerate(iterable):
count = 0
for _ in iterable:
yield (count, _)
count += 1
for i, val in myenumerate((letter for letter in 'abc')):
print i, val
메모리 예외 없이이 함수를 호출 할 수 있으므로 게으르다.
def veryBigHello():
i = 0
while i < 1000000000000000000000000000:
yield "hello"
numbered = enumerate(veryBigHello())
for i, word in numbered:
print i, word
참고 URL : https://stackoverflow.com/questions/3396279/enumerate-ing-a-generator-in-python
반응형
'ProgramingTip' 카테고리의 다른 글
가변 매크로에서 인수를 반복 할 수 있습니까? (0) | 2020.11.14 |
---|---|
Visual Studio 2010의 전역 소스 코드 제어 무시 패턴에는 무엇이 포함되어야합니까? (0) | 2020.11.14 |
현재까지 그루비 노드 (0) | 2020.11.14 |
Python : N 번 목록에 항목 추가 (0) | 2020.11.14 |
SNI는 실제로 브라우저에서 지원합니까? (0) | 2020.11.14 |