French

French - 技术经验
澄其心, 断其欲, 方能悟道
  1. 首页
  2. 编程语言
  3. Python
  4. 正文

Python生成指定数量随机且不重复列表

2021-06-18 2053点热度 2人点赞 0条评论

因为项目需要, 生成一个随机数量且不重复数字列表, 网上的方法没有符合我心意的, 所以写了一个方法

代码如下:

import random


def Get_Random_Number_NO(quantity, min_num=0, max_num=10):
    """
    @编写作者: French \n
    @创建时间: 2021-06-18\n
    @修改时间: 2021-06-18\n
    @功能描述: 生成限定范围内随机数字不重复列表 \n

    Args:
        quantity: 数量
        min_num: 最小数
        max_num: 最大数
        is_contain: 是否包含最大数

    Returns:
        list
    """
    if (max_num - min_num) < quantity:
        raise TypeError("max_num减去min_num的值,必须要大于或等于quantity!")
    random_number_list = []
    while quantity:
        num = random.randint(min_num, max_num)
        try:
            random_number_list.index(num)
        except ValueError:
            random_number_list.append(num)
            quantity -= 1
    return random_number_list


if __name__ == '__main__':
    num_list = Get_Random_Number_NO(quantity=15, min_num=5, max_num=100, is_contain=True)
    print(num_list)

运行结果:

 

本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2021-06-19

French

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2018-2024 French. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备2022008471号-1

川公网安备 51130202000393号