How would I have a single line of code generate more than one random choice from a chosen list?
btw I do have import random at the top of the code
here is my code:
(R[0] = "RED", O[0] = "ORANGE", etc.)
ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]]
ColourSeq = random.choice(ColourList)
print(ColourSeq)
I know at the moment I have only asked it to give me one output, but I would like it to be able to give me four of the items from ColourList in just one line of code.
There can be duplicate outputs.
You can use random.choices instead of random.choice. It is new in version 3.6.
ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]]
ColourSeq = random.choices(ColourList, k=6)
print(ColourSeq)
If you want to allow duplicate values, you can't use random.sample(). You can use a list comprehension:
ColourList = [R[0],O[0],Y[0],G[0],B[0],I[0],V[0]]
ColourSeq = [random.choice(ColourList) for x in range(4)]
print(ColourSeq)
If you want to print those values on separate lines, without the various additions of the list, replace the print statement with
print(*ColourSeq, sep='\n')
or with the longer but clearer
for v in ColourSeq:
print(v)
If you want them printed on the same line but with the list stuff removed, just use the simple
print(*ColourSeq)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With