Flattening a shallow list in Python -


this question has answer here:

is there simple way flatten list of iterables list comprehension, or failing that, consider best way flatten shallow list this, balancing performance , readability?

i tried flatten such list nested list comprehension, this:

[image image in menuitem menuitem in list_of_menuitems] 

but in trouble of nameerror variety there, because name 'menuitem' not defined. after googling , looking around on stack overflow, got desired results reduce statement:

reduce(list.__add__, map(lambda x: list(x), list_of_menuitems)) 

but method unreadable because need list(x) call there because x django queryset object.

conclusion:

thanks contributed question. here summary of learned. i'm making community wiki in case others want add or correct these observations.

my original reduce statement redundant , better written way:

>>> reduce(list.__add__, (list(mi) mi in list_of_menuitems)) 

this correct syntax nested list comprehension (brilliant summary df!):

>>> [image mi in list_of_menuitems image in mi] 

but neither of these methods efficient using itertools.chain:

>>> itertools import chain >>> list(chain(*list_of_menuitems)) 

and @cdleary notes, it's better style avoid * operator magic using chain.from_iterable so:

>>> chain = itertools.chain.from_iterable([[1,2],[3],[5,89],[],[6]]) >>> print(list(chain)) >>> [1, 2, 3, 5, 89, 6] 

if you're looking iterate on flattened version of data structure , don't need indexable sequence, consider itertools.chain , company.

>>> list_of_menuitems = [['image00', 'image01'], ['image10'], []] >>> import itertools >>> chain = itertools.chain(*list_of_menuitems) >>> print(list(chain)) ['image00', 'image01', 'image10'] 

it work on that's iterable, should include django's iterable querysets, appears you're using in question.

edit: reduce anyway, because reduce have same overhead copying items list that's being extended. chain incur (same) overhead if run list(chain) @ end.

meta-edit: actually, it's less overhead question's proposed solution, because throw away temporary lists create when extend original temporary.

edit: j.f. sebastian says itertools.chain.from_iterable avoids unpacking , should use avoid * magic, the timeit app shows negligible performance difference.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -