[Chicago] Resolving lists within lists within lists within .....

Aaron Elmquist elmq0022 at umn.edu
Thu Feb 18 20:43:27 EST 2016


That's true.

I was thinking that it might be beneficial if the routine handled any
nested iterable besides strings which only has __getitem__ implemented.

That may not be a good idea.

Using Brad's isinstance(elment,list) should be better.

Thanks for the feedback.
On Feb 18, 2016 7:22 PM, "Robare, Phillip (TEKSystems)" <proba at allstate.com>
wrote:

> Aaron, unlike Massimo’s elegant one-liner you don’t check that what you
> are iterating over is a list.  Since Python will happily iterate over
> strings, dictionaries, and much more you quickly get into problems when the
> list includes more types than lists and numbers.  I recount this from
> experience when I tried to throw together a flatten routine and pass it a
> data structure that I got from loading a JSON string.
>
>
>
> Phil Robare
>
>
>
> *<snip/>*
>
>
>
> On Thu, Feb 18, 2016 at 1:43 PM, Aaron Elmquist <elmq0022 at umn.edu> wrote:
>
> Douglas,
>
> Here's one more version for you and the rest of the list. It's based on
> Brad's code.  I will let you think about why this version might be better
> or worse.  Also, recursion is great.  It's just too bad it's not one of
> python's strong points.
>
>
> def flatten(lst):
>     for item1 in lst:
>         if hasattr(item1, '__iter__'):
>             for item2 in flatten(item1):
>                 yield item2
>         else:
>             yield item1
>
> print([x for x in flatten([1, [2,3,[4,5,6,[7,8,9]]]]) if x%2 == 1])
>
> y = flatten([1, [2,3,[4,5,6,[7,8,9]]]])
>
> print(next(y))
> print(next(y))
> print(next(y))
> .
> .
> .
> <snip/>
>
> On Wed, Feb 17, 2016 at 9:48 PM, DiPierro, Massimo <
> MDiPierro at cs.depaul.edu> wrote:
>
> here is a one liner:
>
> def flatten(x):
>     return [z for y in x for z in flatten(y)] if isinstance(x,list) else
> [x]
>
>
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20160218/0cc87dcd/attachment-0001.html>


More information about the Chicago mailing list