python中的random.sample()方法有什么作用?

问题描述 投票:29回答:2

我用Google搜索了很多但却找不到它。我想知道使用random.sample()方法,它给出了什么?什么时候应该使用它和一些示例用法。

python random
2个回答
58
投票

documentation说:

random.sample(population,k)

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

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

>>> 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也直接从一个范围工作:

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

除了序列,random.sample也适用于集合:

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

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

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

2
投票

random.sample()也在文本上工作

例:

> text = open("textfile.txt").read() 

> random.sample(text, 5)

> ['f', 's', 'y', 'v', '\n']

\ n也被视为一个字符,因此也可以返回

如果您首先使用split方法,则可以使用random.sample()从文本文件中返回随机单词

例:

> words = text.split()

> random.sample(words, 5)

> ['the', 'and', 'a', 'her', 'of']
© www.soinside.com 2019 - 2024. All rights reserved.