Need a strange sort method...

Ron Adam rrr at ronadam.com
Tue Oct 17 12:56:48 EDT 2006


Ron Adam wrote:
> Neil Cerutti wrote:
>> On 2006-10-16, Tim Chase <python.list at tim.thechases.com> wrote:
>>> If you need it in a flat list, rather than as a list of
>>> chunk_size lists (which are handy for iterating over in many
>>> cases), there are ways of obtaining it, such as the hackish
>>>
>>>>>> sum([a[i::chunk_size] for i in range(chunk_size)], [])
>>> [1, 4, 7, 10, 2, 5, 8, 3, 6, 9]
>>>
>>> There are likely good recipes for flattening a list.  I just
>>> happen not to have any at my fingertips.
>>
>> Actually, there isn't a good recipe in Python for flattening a
>> list. They all come out tasting like Circus Peanuts (Turkish
>> Delight for you non-Yanks).
>>
> 
> 
> Here's two that I came up with.  They are both very fast compared to 
> anything else I've seen.  Maybe they won't taste so much like Peanuts.   
> :-)
> 
> 
> def flatten(L):
>     """ Flatten a list in place.
>     """
>     i = 0
>     while i < len(L):
>         while type(L[i]) is list:
>             L[i:i+1] = L[i]
>         i += 1
>     return L
> 
> def sflatten(sequence):
>     """ Return a flattened sequence as a list.
>     """
>     def iterinner(seq):
>         for s in seq:
>             if hasattr(s, '__iter__'):
>                 for i in iterinner(s):
>                     yield i
>             else:
>                 yield s
>     return list(iterinner(sequence))

Woops,  cut the wrong one...  Replace sflatten above with the following.


def flattened(seq):
     """ Return a flattened sequence as a list.
     """
     def visit(a, x):
         for i in x:
             if not hasattr(i, '__iter__'):
                 a.append(i)
             else:
                 visit(a, i)
     a = []
     visit(a, seq)
     return a


> 
> Cheers,
>    Ron Adam



More information about the Python-list mailing list