Need a strange sort method...

R

Ron Adam

Ron said:
Neil said:
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) is list:
L[i:i+1] = L
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,182
Latest member
BettinaPol

Latest Threads

Top