shuffling elements of a list

Peter Otten __peter__ at web.de
Fri Jun 2 07:50:46 EDT 2006


Iain King wrote:

> or shorter but possible less readable (and only in 2.4+):
> 
> def shuffle(data):
>     return [y[1] for y in sorted([(random(), x) for x in data])]

sorted() and list.sort() will happily accept a key function argument and
then do the decorating/undecorating for you:

>>> from random import random
>>> def key(item): return random()
...
>>> def shuffled(items):
...     return sorted(items, key=key)
...
>>> shuffled(range(10))
[6, 5, 3, 4, 8, 9, 0, 7, 1, 2]

> or in nicer python, but still when you're mysitified by map and lambda
> (like me):

Turning the key() function into a lambda is left as an exercise :-)

Peter




More information about the Python-list mailing list