티스토리 뷰

Python

[Python] Generator 합치기

developer0hye 2023. 4. 26. 23:43

https://stackoverflow.com/questions/3211041/how-to-join-two-generators-or-other-iterables-in-python

 

How to join two generators (or other iterables) in Python?

I want to change the following code for directory, dirs, files in os.walk(directory_1): do_something() for directory, dirs, files in os.walk(directory_2): do_something() to this code: for

stackoverflow.com

 

Python Generator는 '+' 연산을 지원하지 않는다.

 

만약 두 개의 Generator를 합치려는 시도를 '+'를 사용하여 하려한다면 아래와 같은 Error를 보게될것이다.

 

TypeError: unsupported operand type(s) for +: 'generator' and 'generator'

 

'+' 대신 itertools의 chain을 활용하면 두개의 generator를 쉽게 합칠 수 있다.

from itertools import chain

def generator1():
    for item in 'abcdef':
        yield item

def generator2():
    for item in '123456':
        yield item

generator3 = chain(generator1(), generator2())
for item in generator3:
    print(item)

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함