can there be ‘cross-referencing’ generators in Python? [duplicate]

This question already has an answer here:

Imagine the following piece of code which generates a list of file sizes from the current directories’ files:

_sizes = []
for _base, _dirs, _files in os.walk('.'):
    for _file in _files:
        _size = getsize(join(_base, _file))

I wonder whether I can create a nested generator from this – like:

_sizes = [getsize(join(_base, _file)) 
              for _file in _files 
                  for [_base, _dirs, _files in os.walk('.')]]

This is syntactically incorrect of course since [_base, _dirs, _files in os.walk('.')] is not correct generator syntax. What I need now is a way to iterate through a sub-element from a list (_files) while referencing another one (_base) (what I called cross-referencing in the title).

I now wonder if I just can’t see the obvious or if this is approach is not valid in general.

Source: syntax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.