is there a shorter way to write this
Stephen Hansen
apt.shansen at gmail.com
Thu Jan 29 09:35:05 EST 2009
On Thu, Jan 29, 2009 at 6:11 AM, garywood <pythonsky at sky.com> wrote:
> I had a task in a book to pick 5 items from a list of 26 ensuring the
> items are not repeated
>
>
If the list is unique of 26 elements is guaranteed to be unique, simply:
>>> import random
>>> random.sample(list, 5)
['g', 'y', 'i', 'n', 'x']
If the list isn't unique:
>>> import random
>>> random.sample(set(list), 5)
['r', 'e', 'b', 'k', 'i']
If you want to combine them all into a single word as you do in your
example:
>>> import random
>>> ''.join(random.sample(set(list), 5))
'wmhsq'
--Stephen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090129/bb25b66c/attachment-0001.html>
More information about the Python-list
mailing list