[Chicago] Resolving lists within lists within lists within .....
Adam Forsyth
adam at adamforsyth.net
Thu Feb 18 20:55:39 EST 2016
Phil,
That's generally true, but one small correction. Aaron's solution won't
actually won't flatten strings, as they don't have "__iter__" methods. They
implement iteration because they take sequential numeric indexes starting
at 0, and raise an IndexError after the index passed is too large.
Adam
On Feb 18, 2016 19:22, "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/f5f8b32c/attachment.html>
More information about the Chicago
mailing list