syntax - can there be 'cross-referencing' generators in Python? -


this question has answer here:

imagine following piece of code generates list of file sizes current directories' files:

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

i wonder whether can create nested generator - s.th. like:

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

this syntactically incorrect of course since [_base, _dirs, _files in os.walk('.')] not correct generator syntax. need way iterate through sub-element list (_files) while referencing 1 (_base) (what called cross-referencing in title).

i wonder if can't see obvious or if approach not valid in general.

you can this:

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

if want generator, use generator expression (replacing [] ()):

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

see list comprehension in python tutorial.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -