Get a random sample with replacement

前端 未结 4 1933
一整个雨季
一整个雨季 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: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.

提交回复
热议问题