python中的random.sample()方法有什么作用? [英] What does random.sample() method in python do?

查看:1148
本文介绍了python中的random.sample()方法有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Google搜索了很多,但是找不到.我想知道random.sample()方法的用途,它有什么作用?什么时候应该使用它以及一些示例用法.

I Googled it a lot but could not found it. I want to know the use of random.sample() method and what does it give? When should it be used and some example usage.

推荐答案

根据

random.sample(人口k)

random.sample(population, k)

返回长度为k的唯一元素列表 从总体序列中选择.用于随机抽样而无需 替换.

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

基本上,它从序列中选取k个唯一的随机元素(样本):

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample也可以直接在范围内工作:

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

除序列外,random.sample也可用于集合:

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

但是,random.sample不适用于任意迭代器:

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

这篇关于python中的random.sample()方法有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆