set & random.choice question

Dennis Benzinger Dennis.Benzinger at gmx.net
Wed Dec 14 22:13:34 CET 2005


stevecanfield at yahoo.com schrieb:
> I want to do something like this:
> 
>   from random import choice
>   x = set(("jenny", "jacqui", "claire", "chris", "tracy"))
>   somebody = random.choice(x)
> 
> but I bet a "TypeError: unindexable object" error. Any suggestions for
> an elegant workaround?
> 
> I'm using set because I want to know that I have a collection of unique
> objects.
> 
> steve
> 

import random

x = set(("jenny", "jacqui", "claire", "chris", "tracy"))


def draw_from_set(a_set):
     random_index = random.randint(0, len(x) - 1)

     for i, name in enumerate(x):
         if i == random_index:
             return name

somebody = draw_from_set(x)

print somebody


Bye,
Dennis



More information about the Python-list mailing list