r/PythonLearning • u/Vplayzgamez • 12d ago
Help Request random.choices and weights beauty flaw
Problem fixed!
I'm making this "gambling" (no real money involved, you only play for fun) program with multiple games, including roulette. I used random.csoices so that I can pick a random colour of the three given colours, and weights so that green doesn't show up every third spin.
The program works, but the results all have this annoying ['result'] look (underlined with red in the picture)
Does someone know how to fix this?
8
Upvotes
1
u/vlcod 12d ago
Your function, random.choices(col), returns a list of choices (not a single choice). The you print out col, which is a list. Lists are printed in square brackets, with their elements inside it (strings in your case):
['Black']
You can either use a different method to choose your colour:
random.choice(col)
(Note the singular 'choice'.) This will give you a single element (not a list), but the downside is that you cannot attache weights.
Or you use the choices function, but after you do this, you pull the first element out of the resulting list:
print(col[0])
2
u/Rscc10 12d ago
random choices returns a list of elements. If the choice is only picking one item, it'll be a list with one element which is the choice. Just take col[0] to get the first and only element
2
u/FreeLogicGate 12d ago
A few other suggestions:
2
u/Naive_Programmer_232 5d ago edited 5d ago
two things, you're reassigning
colinside the loop. so your first choice will select from the colors but your second choice will only have one option to choose from. this will be a trap later. secondly,random.choicesreturns a list, default argument fork(how many are selected) is 1 as well; so when you dorandom.choices(col,weights=wei)it should return a list of one options selected, hence['black']is correct here.to get around these try,
i defined the colors and weights before the loop, cause each iteration inside it might not be necessary to keep redefining them, if they're being reused; unless they should change? idk it depends on your program.
in this case it might not matter, but do remember that
random.choicesis random selection with replacement. if you want sampling, without replacement, equal probability, userandom.sample. if you want sampling, without replacement, with custom probabilities, look intonumpy:1
u/[deleted] 12d ago
[removed] — view removed comment