Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2 iterators or generators
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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().
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  itertools.zip_shortest() fo unequal iterators Skaperen 10 6,582 Dec-27-2019, 12:17 AM
Last Post: Skaperen
  how to join 2 iterators Skaperen 2 2,612 Sep-11-2019, 07:19 PM
Last Post: Skaperen
  iterating over 2 iterators Skaperen 2 2,215 Jun-07-2019, 11:37 PM
Last Post: Skaperen
  Iterators mp3909 3 2,981 Mar-16-2018, 09:42 PM
Last Post: nilamo
  Using Generators and their expressions BeerLover 3 4,488 Mar-18-2017, 11:06 PM
Last Post: Ofnuts
  Stacking generators Ofnuts 2 19,275 Sep-18-2016, 08:36 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020