Python Forum
2 iterators or generators - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: 2 iterators or generators (/thread-7324.html)



2 iterators or generators - Skaperen - Jan-04-2018

i want to be able to interleave two or more iterator or generators, including stepping one or more of them fewer or more times as coded logic may dictate. for example, consider os.walk('file-tree-one') and os.walk('file-tree-two') where these two file trees have identically named files and the 2nd one has an extra file somewhere. normally i can do code like:
    t1 = []
    for dn, dl, fl in os.walk('file-tree-one'):
        for f in fl:
            t1.append(dn+'/'+f)
    print('\n'.join(t1))
and build a flat list of files from the tree (this code sample does not include directories). something has to keep the state of how far along this is as it runs and i assume that would be the iterator. but how would this be done to interleave two of them? some documentation mentions a next() call. i tried a .next() method on os.walk(), but that attribute does not exist. anyone know what is going on?


RE: 2 iterators or generators - Gribouillis - Jan-04-2018

You can use the built-in function next() with any iterator
t1 = []
walk1 = os.walk('file-tree-one')
while True:
    dn, dl, fl = next(walk1)
    for f in fl:
        t1.append(os.path.join(dn, f))
You need to handle the exception StopIteration or use the 'default' parameter in next().