파이썬에서 두 생성기를 결합하는 방법?
다음 코드를 변경하고 싶습니다
for directory, dirs, files in os.walk(directory_1):
do_something()
for directory, dirs, files in os.walk(directory_2):
do_something()
이 코드로 :
for directory, dirs, files in os.walk(directory_1) + os.walk(directory_2):
do_something()
오류가 발생합니다.
+에 대해 지원되지 않는 피연산자 유형 : 'generator'및 'generator'
파이썬에서 두 생성기를 결합하는 방법?
itertools.chain()
해야 한다고 생각 합니다.
코드 예 :
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
간단한 예 :
from itertools import chain
x = iter([1,2,3]) #Create Generator Object (listiterator)
y = iter([3,4,5]) #another one
result = chain(x, y) #Chained x and y
Python (3.5 이상)에서는 다음을 수행 할 수 있습니다.
def concat(a, b):
yield from a
yield from b
itertools.chain.from_iterable을 사용하면 다음과 같은 작업을 수행 할 수 있습니다.
def genny(start):
for x in range(start, start+3):
yield x
y = [1, 2]
ab = [o for o in itertools.chain.from_iterable(genny(x) for x in y)]
print(ab)
여기 에 중첩 된 s 와 함께 생성기 표현식 을 사용하고 있습니다 for
.
a = range(3)
b = range(5)
ab = (i for it in (a, b) for i in it)
assert list(ab) == [0, 1, 2, 0, 1, 2, 3, 4]
생성기를 개별적으로 유지하면서 동시에 반복적으로 반복하려면 zip ()을 사용할 수 있습니다.
참고 : 두 발전기 중 짧은 쪽에서 반복이 중지됩니다.
예를 들면 다음과 같습니다.
for (root1, dir1, files1), (root2, dir2, files2) in zip(os.walk(path1), os.walk(path2)):
for file in files1:
#do something with first list of files
for file in files2:
#do something with second list of files
Lets say that we have to generators (gen1 and gen 2) and we want to perform some extra calculation that requires the outcome of both. We can return the outcome of such function/calculation through the map method, which in turn returns a generator that we can loop upon.
In this scenario, the function/calculation needs to be implemented via the lambda function. The tricky part is what we aim to do inside the map and its lambda function.
General form of proposed solution:
def function(gen1,gen2):
for item in map(lambda x, y: do_somethin(x,y), gen1, gen2):
yield item
One can also use unpack operator *
:
concat = (*gen1(), *gen2())
NOTE: Works most efficiently for 'non-lazy' iterables. Can also be used with different kind of comprehensions. Preferred way for generator concat would be from the answer from @Uduse
All those complicated solutions...
just do:
for dir in director_1, directory_2:
for directory, dirs, files in os.walk(dir):
do_something()
If you really want to "join" both generators, then do :
for directory, dirs, files in
[x for osw in [os.walk(director_1), os.walk(director_2)]
for x in osw]:
do_something()
참고URL : https://stackoverflow.com/questions/3211041/how-to-join-two-generators-in-python
'IT story' 카테고리의 다른 글
배열에 다른 배열의 값이 포함되어 있습니까? (0) | 2020.06.12 |
---|---|
Git을 사용하여 로컬과 원격 사이의 변화를 어떻게 찾을 수 있습니까? (0) | 2020.06.12 |
알림 클릭 : 활동이 이미 열려 있습니다 (0) | 2020.06.12 |
Angular 2-this.router.parent.navigate ( '/ about')를 사용하여 다른 경로로 이동하는 방법? (0) | 2020.06.12 |
Visual Studio Code Editor에서 사용되는 글꼴과 글꼴을 변경하는 방법은 무엇입니까? (0) | 2020.06.12 |