A query about list
Robert Brewer
fumanchu at amor.org
Thu Oct 9 16:55:24 EDT 2003
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
More information about the Python-list
mailing list