日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python random.sample

發布時間:2023/12/20 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python random.sample 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

random.sample 從集合或者序列中,無放回采樣

用法:

sample_list=random.sample(population, k) # population : 可以是一個集合,也可以是序列(list,tuple,或者字符串) # k : 0<= k<= len(population) # 返回一個list,如果是字符串的話,返回的是['index1','index2']隨機選擇的索引值 # 注意:不會改變原來的 population

測試:

import randomrandom.seed(66) a1=list(range(0,10)) print(a1,type(a1)) b1= random.sample(a1,2) print(b1) print(a1) """ 結果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'> [1, 4] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """a2=tuple(range(0,10)) print(a2,type(a2)) b2= random.sample(a2,2) print(b2) print(a2) """ 結果: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) <class 'tuple'> [6, 3] (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) """a3='1234567890' print(a3,type(a3)) b3= random.sample(a3,2) print(b3) print(a3) """ 結果: 1234567890 <class 'str'> ['8', '5'] 1234567890 """a4=dict(spam = 1, egg = 2, bar =3) print(a4,type(a4)) b4= random.sample(a4,2) print(b4) print(a4) # 報錯:不能處理dicta5 = set(("Google", "Runoob", "Taobao")) print(a5,type(a5)) b5= random.sample(a5,2) print(b5) print(a5) """ 結果: {'Runoob', 'Taobao', 'Google'} <class 'set'> ['Taobao', 'Runoob'] {'Runoob', 'Taobao', 'Google'} """

源代碼:

def sample(self, population, k):"""Chooses k unique random elements from a population sequence or set.Returns a new list containing elements from the population whileleaving the original population unchanged. The resulting list isin selection order so that all sub-slices will also be valid randomsamples. This allows raffle winners (the sample) to be partitionedinto grand prize and second place winners (the subslices).Members of the population need not be hashable or unique. If thepopulation contains repeats, then each occurrence is a possibleselection in the sample.To choose a sample in a range of integers, use range as an argument.This is especially fast and space efficient for sampling from alarge population: sample(range(10000000), 60)"""# Sampling without replacement entails tracking either potential# selections (the pool) in a list or previous selections in a set.# When the number of selections is small compared to the# population, then tracking selections is efficient, requiring# only a small set and an occasional reselection. For# a larger number of selections, the pool tracking method is# preferred since the list takes less space than the# set and it doesn't suffer from frequent reselections.if isinstance(population, _Set):population = tuple(population)if not isinstance(population, _Sequence):raise TypeError("Population must be a sequence or set. For dicts, use list(d).")randbelow = self._randbelown = len(population)if not 0 <= k <= n:raise ValueError("Sample larger than population or is negative")result = [None] * ksetsize = 21 # size of a small set minus size of an empty listif k > 5:setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big setsif n <= setsize:# An n-length list is smaller than a k-length setpool = list(population)for i in range(k): # invariant: non-selected at [0,n-i)j = randbelow(n-i)result[i] = pool[j]pool[j] = pool[n-i-1] # move non-selected item into vacancyelse:selected = set()selected_add = selected.addfor i in range(k):j = randbelow(n)while j in selected:j = randbelow(n)selected_add(j)result[i] = population[j]return result

總結

以上是生活随笔為你收集整理的python random.sample的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。