do you master list comprehensions?
Fredrik Lundh
fredrik at pythonware.com
Tue Dec 14 02:44:10 EST 2004
James Stroud wrote:
> Here is one for arbitrary depth:
>
> def unroll(ary):
> unrolled = []
> for item in ary:
> # add test for your favorite sequence type
> if ( type(item) == types.ListType or \
> type(item) == types.TupleType \
> ):
> unrolled.extend(unroll(item))
> else:
> unrolled.append(item)
> return unrolled
>
>>>> unroll([[1, 2, 3], ('fred', 'barney', ['wilma', 'betty']), 'dino'])
> [1, 2, 3, 'fred', 'barney', 'wilma', 'betty', 'dino']
or, shorter:
>>> from Tkinter import _flatten as unroll
>>> (1, 2, 3, 'fred', 'wilma', 'betty', 'dino')
(alright, it returns a tuple, but that can be easily fixed, if necessary)
</F>
More information about the Python-list
mailing list