Get a random sample with replacement

前端 未结 4 1922
一整个雨季
一整个雨季 2020-12-16 09:26

I have this list:

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

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

Runni

相关标签:
4条回答
  • 2020-12-16 09:47

    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']
    
    0 讨论(0)
  • 2020-12-16 09:56

    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.

    0 讨论(0)
  • 2020-12-16 09:58

    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)
    
    0 讨论(0)
  • 2020-12-16 09:59

    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))
    
    0 讨论(0)
提交回复
热议问题