python中的random.sample()方法有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22741319/
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
What does random.sample() method in python do?
提问by kartikeykant18
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()
方法的用途以及它提供了什么?什么时候应该使用它以及一些示例用法。
采纳答案by alecxe
According to documentation:
根据文档:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
random.sample(人口,k)
返回从种群序列中选择的唯一元素的 ak 长度列表。用于不放回的随机抽样。
Basically, it picks k unique random elements, a sample, from a sequence:
基本上,它从序列中挑选 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
works also directly from a range:
random.sample
也可以直接从一个范围内工作:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
除了序列,也random.sample
适用于集合:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
但是,random.sample
不适用于任意迭代器:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
回答by asd0999
random.sample()
also works on text
random.sample()
也适用于文本
example:
例子:
> text = open("textfile.txt").read()
> random.sample(text, 5)
> ['f', 's', 'y', 'v', '\n']
\nis also seen as a character so that can also be returned
\n也被视为一个字符,因此也可以返回
you could use random.sample()
to return random words from a text file if you first use the split method
random.sample()
如果您首先使用 split 方法,您可以使用从文本文件中返回随机单词
example:
例子:
> words = text.split()
> random.sample(words, 5)
> ['the', 'and', 'a', 'her', 'of']