zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Python】Python列表 随机弹出一个/几个元素

Python列表 一个 元素 几个 随机
2023-09-27 14:26:45 时间

在这里插入图片描述

前言

记录一下在Python的列表中随机pop指定数量元素的操作。水文一篇!

在实际使用中有这个需求,搜索引擎找了找没有想要的,于是自己捣鼓了一下;
直接for循环也可以实现,写成函数的话,看起来似乎好看些😁


知识点📖📖

分别是内置类 listrandom 模块的两个函数~

函数释义
list.pop删除并返回索引处的项目(
random.choice从非空序列中选择一个随机元素

实现

先来看看 random.choice 函数的定义,

>>> help(choice)
Help on method choice in module random:
choice(seq) method of random.Random instance
    Choose a random element from a non-empty sequence.

再来看看list 中的pop函数定义

  • 删除并返回索引处的项目(默认为最后,即index=-1);
  • 如果列表为空或索引超出范围,将引发IndexError

>>> help(list.pop)
Help on built-in function pop:
pop(index=-1, /) method of builtins.list instance
    Remove and return item at index (default last).
    
    Raises IndexError if list is empty or index is out of range.

根据上面两个函数的定义,在实现随机抛出指定数量时候只需要注意:

  • 列表不为空
  • 不超出索引范围

就可以实现随机抛出list中指定数量的元素啦!

下面就开始写代码吧!!


代码

  • _list:列表
  • count:抛出元素的数量
  • isRandom 指定是否随机抛出
# -*- coding: utf-8 -*-
# @Author : Frica01
# @Time   : 2023-03-12 21:49
# @Name   : demo.py

from random import choice


def pop_elements(_list, count, isRandom=None):
    """
    抛出指定数量的元素

    Args:
        _list(list): 列表
        count(int): 抛出元素的位数量
        isRandom(bool): 是否随机

    Raises:
        IndexError

    Returns:
        列表抛出的结果
    """
    # 判断是否为空
    assert _list, '列表不能为空'
    # 不超出索引
    if _list.__len__() < count:
        raise IndexError('超出索引范围')
    # 是否随机
    if isRandom:
        return [_list.pop(choice(range(0, _list.__len__()))) for idx in range(count)]
    return [_list.pop(-1) for idx in range(count)]


if __name__ == '__main__':
    test_list = list(range(10))
    print('原列表: ', test_list)
    print('抛出的元素列表', pop_elements(test_list, 5, isRandom=True))
    print('操作后列表: ', test_list)

后话

本次分享到此结束,
see you~🐱‍🏍🐱‍🏍