syntax - can there be 'cross-referencing' generators in Python? -
this question has answer here:
- nested loops using list comprehension 3 answers
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 )
Comments
Post a Comment