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相关推荐

  1. python random.sample()和random.choices()

    python random.sample()和random.choices() s = random.sample(list, k) sample 是相当于不放回抽样.如果列表中的数据不重复,抽取数据 ...

  2. python——random.sample()的用法

    https://www.cnblogs.com/fish-101/p/11339909.html

  3. python中sample是什么意思_基于Python中random.sample()的替代方案

    python中random.sample()方法可以随机地从指定列表中提取出N个不同的元素,但在实践中发现,当N的值比较大的时候,该方法执行速度很慢,如: numpy random模块中的choice ...

  4. Python random模块sample、randint、shuffle、choice随机函数

    一.random模块简介 Python标准库中的random函数,可以生成随机浮点数.整数.字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据等. 二.random模块重要函数 1 ).ra ...

  5. python random sample_python中的sample什么意思

    sample是random模块中的一个函数 表达式为:random.sample(sequence, k) 它的作用是从指定序列中随机获取指定长度的片断并随机排列,结果以列表的形式返回.注意:samp ...

  6. Python random 随机函数(random、uniform、randint、choice、choices、randrange、shuffle、sample)

    注意:当前使用环境为 Python 3.11.0 1.random.random() 用于生成一个 0 到 1 的随机符点数: 0 <= n < 1.0. # 代码 import rand ...

  7. python random函数sample_Python random.seed() random.sample()函数使用

    random.seed(0)作用:使得随机数据可预测,即只要seed的值一样,后续生成的随机数都一样. 一.不设置seed() import random list = [1, 2, 3, 4, 5, ...

  8. python随机数random.sample

    import random #导入模块 #1.从一个数组中随机返回n个元素:random.sample(数组,n) a=[1,2,3,4,5,6,7,8,9,10] #定义一个数组 b=random. ...

  9. python random库生成伯努利随机数的方法_Python使用random模块生成随机数操作实例详解...

    本文实例讲述了Python使用random模块生成随机数操作.分享给大家供大家参考,具体如下: 今天在用Python编写一个小程序时,要用到随机数,于是就在网上查了一下关于Python生成各种随机数的 ...

  10. python random模块中的指令_10分钟让你掌握python编程中random模块功能使用,非常详细...

    原标题:10分钟让你掌握python编程中random模块功能使用,非常详细 python作为一门高级编程语言,它的定位是优雅.明确和简单.阅读Python编写的代码感觉像在阅读英语一样,这让使用者可 ...

最新文章

  1. Pure-FTPd服务器
  2. 认识MySQL Replication
  3. TCP/IP 协议简单分析
  4. Android三个Version的作用
  5. const应用和作用
  6. 用C语言实现三子棋游戏
  7. DCMTK:类OFMap的测试程序
  8. 提高雅思听力速度必须反复练耳朵别无捷径
  9. 可以上传视频的网站大全
  10. springboot整合junit_springBoot整合junit(笔记)
  11. 【mybatis深度历险系列】mybatis中的动态sql
  12. 梧桐计划发布!百度智能云携手合作伙伴共创“云智一体”繁荣新生态
  13. 20位大厂面试官推荐的Java面试八股文
  14. 工作室多拨宽带如何优化?
  15. 链接提交提示安全验证,网站辅助快排不行了吗?
  16. 华为OD机试真题 Java 实现【服务中心选址】【2023 Q1 | 200分】
  17. libusb系列-007-Qt下使用libusb1.0.26源码
  18. 猿创征文|基于Java+SpringBoot+vue学生学习平台详细设计实现
  19. 设计一个长方体类Cuboid
  20. ubuntu 软件包管理

热门文章

  1. Beyond Compare 4 “授权秘钥已被吊销“ 的解决办法
  2. 【雅思大作文考官范文】——第八篇:recycling essay(垃圾回收)
  3. 【网络流24题】火星探险问题
  4. java编程填空及答案_JAVA填空题标准答案(103题)
  5. js 图片类型mage/jpeg, image/bmp, image/gif ,image/png
  6. Linux中招挖矿木马如何处置,附带解决方案
  7. [转]【总结】clc和clear命令的使用
  8. 强强联合丨谱尼测试与北大医疗鲁中医院开启战略合作新征程
  9. Python爬取曾今的K歌
  10. [内附完整源码和文档] 基于PHP的网上购物系统设计与实现