A query about list
Robert Brewer
fumanchu at amor.org
Sun Oct 12 04:48:40 EDT 2003
If you're going to gloss over all errors *and* just print, this works in
Python 2.2:
>>> def depth(seq):
... for item in seq:
... try: depth(item)
... except: print item,
...
>>> a = [1,[2,3,4],5,6,7,[8,9,10],11,12]
>>> depth(a)
1 2 3 4 5 6 7 8 9 10 11 12
>>> a = [1,[2,3,4],5,6,7,['mangos in syrup',9,10],11,12]
>>> depth(a)
1 2 3 4 5 6 7 m a n g o s i n s y r u p 9 10 11 12
You don't need "continue" or "len".
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
> -----Original Message-----
> From: Tony Clarke [mailto:a.clarke11 at ntlworld.com]
> Sent: Sunday, October 12, 2003 1:40 AM
> To: python-list at python.org
> Subject: Re: A query about list
>
>
> "Robert Brewer" <fumanchu at amor.org> wrote in message
> news:<mailman.1065733220.31901.python-list at python.org>...
> > Dave Benjamin wrote:
> > > Santanu Chatterjee wrote:
> > > > I am very new to python. I have a query about
> > > > list in python.
> > > >
> > > > Suppose I have a list
> > > > a = [1,[2,3,4],5,6,7,[8,9,10],11,12]
> > > > I want to know if there is any simple python
> > > > facility available that would expand the above list
> > > > to give
> > > > a = [1,2,3,4,5,6,7,8,9,10,11,12]
> > > >
> > > Normally, I'd suggest "reduce(operator.add, ...)" to flatten
> > > a list, but
> > > since you've got some "naked" entries, that won't work...
> > >
> > > >>> def merge(x, y):
> > > ... if type(y) is type([]): return x + y
> > > ... return x + [y]
> > > ...
> > > >>> reduce(merge, a, [])
> > > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> > >
> >
> > Neat trick with the third parameter to reduce! Didn't know
> about that
> > behavior. That cuts my long one-liner down from:
> >
> > >>> reduce(lambda x, y: {type([]): x}.get(type(x), [x]) + {type([]):
> > y}.get(type(y), [y]), a)
> >
> > to just:
> >
> > >>> reduce(lambda x, y: x + {type([]): y}.get(type(y), [y]), a, [])
> > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> >
> > /shudder. But it's fun. :)
> >
> >
> > Robert Brewer
> > MIS
> > Amor Ministries
> > fumanchu at amor.org
>
>
>
> How about this single function (although not a single line:<), which
> also works for any kind of sequence, and can cope with different types
> in the sequence:
>
> a = [1,[2,3,4],5,6,7,[8,9,10],11,12]
>
> def depth(sequence):
> for item in sequence:
> try:
> b=len(item)
> depth(item)
> except:
> print item,
> continue
>
> depth(a)
>
> I think this is a precursor to generators, but I'm still on Python
> 2.1.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list