![](/img/trans.png)
[英]What is the difference between random.sample and random.shuffle in Python
[英]What does the random.sample() method in Python do?
我想知道random.sample()
方法的使用,它有什么作用? 什么時候應該使用它以及一些示例用法。
根據文檔:
random.sample(人口,k)
返回從種群序列中選擇的唯一元素的 ak 長度列表。 用於不放回的隨機抽樣。
基本上,它從序列中挑選 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).
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']
random.sample(population, k)
它用於從總體中隨機抽樣長度為'k'
的樣本。 返回從總體序列或集合中選擇的唯一元素的'k'
長度列表
它返回一個新列表並保持原始種群不變,結果列表按選擇順序排列,因此所有子切片也將是有效的隨機樣本
我舉了一個例子,在這個例子中我隨機拆分了一個數據集。 它基本上是一個函數,在該函數中,您將x_train(population)
作為參數傳遞,並將60%
數據的索引作為D_test
。
import random
def randomly_select_70_percent_of_data_from_1_to_length(x_train):
return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))
從隨機導入 * lst1 = 樣本(范圍(0, 1000), 100) lst2 = 樣本(范圍(0, 1000), 100) print(lst1) print(lst2) print(set(lst1).intersection(set(lst2 )))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.