Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have multiple random outputs from a single line of code (python)

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.

like image 446
matt6297 Avatar asked Nov 21 '25 04:11

matt6297


2 Answers

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)
like image 175
nokta Avatar answered Nov 22 '25 18:11

nokta


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)
like image 44
Rory Daulton Avatar answered Nov 22 '25 17:11

Rory Daulton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!