AI编程助手
AI免费问答

分享Python random生成某区间内不重复的N个随机数的方法实例

零下一度   2017-05-20 14:58   6700浏览 原创

在近期进行的一个实验中,需要将数据按一定比例随机分割为两个部分。这一问题的核心其实就是产生不重复随机数的问题。首先想到的递归的方法,然后才发现python中居然已经提供了此方法的函数,可以直接使用。具体代码如下:

#生成某区间内不重复的N个随机数的方法
import random;

#1、利用递归生成
resultList=[];#用于存放结果的List
A=1; #最小随机数
B=10 #最大随机数
COUNT=10

#生成随机数的递归数学,参数counter表示当前准备要生成的第几个有效随机数
def generateRand(counter): 
    tempInt=random.randint(A,B); # 生成一个范围内的临时随机数,
    if(counter<p>结果:</p><p><span style="font-size:18px"><img src="https://img.php.cn/upload/article/000/001/506/3f415bf170e076b49aa2cada1cd459b4-0.png?x-oss-process=image/resize,p_40" alt=""><br></span></p><p>【相关推荐】<br></p><p>1. <a href="http://www.php.cn/python-tutorials-362662.html" target="_self">详解Python标准库中数学与随机数 (math包,random包)</a></p><p>2. <a href="http://www.php.cn/python-tutorials-362661.html" target="_self">Python random() 函数的实例教程</a></p><p>3. <a href="http://www.php.cn/python-tutorials-362660.html" target="_self">分享一篇Python中random(随机生成数)的实例教程</a></p><p>4. <a href="http://www.php.cn/python-tutorials-362664.html" target="_self">分享Python中random模块生成随机数的实例教程</a></p><p>5. <a href="http://www.php.cn/python-tutorials-227027.html" target="_self">Python random模块(获取随机数)常用方法和使用例子</a></p><p>6. <a href="http://www.php.cn/python-tutorials-84828.html" target="_self">Python random模块常用方法</a></p><p>7. <a href="http://www.php.cn/python-tutorials-350681.html" target="_self">Python 模块学习:random 随机数生成</a></p>

Python免费学习笔记(深入):立即学习
在学习笔记中,你将探索 Python 的核心概念和高级技巧!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。