Get a random sample with replacement

2019-02-11 19:30发布

问题:

I have this list:

colors = ["R", "G", "B", "Y"]

and I want to get 4 random letters from it, but including repetition.

Running this will only give me 4 unique letters, but never any repeating letters:

print(random.sample(colors,4))

How do I get a list of 4 colors, with repeating letters possible?

回答1:

In Python 3.6, the new random.choices() function will address the problem directly:

>>> from random import choices
>>> colors = ["R", "G", "B", "Y"]
>>> choices(colors, k=4)
['G', 'R', 'G', 'Y']


回答2:

With random.choice:

print([random.choice(colors) for _ in colors])

If the number of values you need does not correspond to the number of values in the list, then use range:

print([random.choice(colors) for _ in range(7)])

From Python 3.6 onwards you can also use random.choices (plural) and specify the number of values you need as the k argument.



回答3:

Try numpy.random.choice (documentation numpy-v1.13):

import numpy as np
n = 10 #size of the sample you want
print(np.random.choice(colors,n))


回答4:

This code will produce the results you require. I have added comments to each line to help you and other users follow the process. Please feel free to ask any questions.

import random

colours = ["R", "G", "B", "Y"]  # The list of colours to choose from
output_Colours = []             # A empty list to append results to
Number_Of_Letters = 4           # Allows the code to easily be updated

for i in range(Number_Of_Letters):  # A loop to repeat the generation of colour
    output_Colours.append(random.sample(colours,1)) # append and generate a colour from the list

print (output_Colours)