随机获取替换样品 [英] Get a random sample with replacement
本文介绍了随机获取替换样品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个列表:
colors = ["R", "G", "B", "Y"]
我想从中得到4个随机字母,但包括重复字母.
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:
print(random.sample(colors,4))
如何获得4种颜色的列表,并可能重复字母?
How do I get a list of 4 colors, with repeating letters possible?
推荐答案
在Python 3.6中,新的 random.choices() 函数将直接解决该问题:
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']
这篇关于随机获取替换样品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文