set & random.choice question

S

stevecanfield

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
 
L

Lawrence Oluyede

Il 2005-12-14 said:
I want to do something like this:

from random import choice
x = set(("jenny", "jacqui", "claire", "chris", "tracy"))
somebody = random.choice(x)

import random
x = set(("jenny", "jacqui", "claire", "chris", "tracy"))
somebody = random.choice(list(x))

You must turn back it into a list, set has no notion of indexing
 
C

Christophe Delord

Hello,

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?

What about somebody = random.choice(list(x)) ?


Christophe.
 
D

Dennis Benzinger

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
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top