Python 获取带有替换的随机样本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43281886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a random sample with replacement
提问by kev xlre
I have this list:
我有这个清单:
colors = ["R", "G", "B", "Y"]
and I want to get 4 random letters from it, but including repetition.
我想从中得到 4 个随机字母,但包括重复。
Running this will only give me 4 unique letters, but never any repeating letters:
运行这个只会给我 4 个独特的字母,但不会有任何重复的字母:
print(random.sample(colors,4))
How do I get a list of 4 colors, with repeating letters possible?
如何获得 4 种颜色的列表,并且可能有重复的字母?
回答by Raymond Hettinger
In Python 3.6, the new random.choices()function will address the problem directly:
在 Python 3.6 中,新的random.choices()函数将直接解决这个问题:
>>> from random import choices
>>> colors = ["R", "G", "B", "Y"]
>>> choices(colors, k=4)
['G', 'R', 'G', 'Y']
回答by trincot
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
:
如果您需要的值数量与列表中的值数量不对应,则使用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 kargument.
从 Python 3.6 开始,您还可以使用random.choices
(复数)并指定您需要的值数量作为k参数。
回答by Priyank
Try numpy.random.choice
(documentation numpy-v1.13):
尝试numpy.random.choice
(文档 numpy-v1.13):
import numpy as np
n = 10 #size of the sample you want
print(np.random.choice(colors,n))
回答by CodeCupboard
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)