【Python】Python列表 随机弹出一个/几个元素
2023-09-27 14:26:45 时间
前言
记录一下在Python的列表中随机pop指定数量元素的操作。水文一篇!
在实际使用中有这个需求,搜索引擎找了找没有想要的,于是自己捣鼓了一下;
直接for循环也可以实现,写成函数的话,看起来似乎好看些😁
知识点📖📖
分别是内置类 list 和 random 模块的两个函数~
函数 | 释义 |
---|---|
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~🐱🏍🐱🏍
相关文章
- Python语法基础_03.字符串、列表、字典
- python对列表中的字典进行排序
- Python列表一个星号,字典dict前边跟两个星号是什么意思?
- Python VS VBA 读取Excel中的文本框组件
- python中functools.cache用法详解及缓存策略问题
- 详解Python列表(list)的方法sort()的第一个参数key【简单清晰明了的讲解】
- 70 python - 列表推导式
- python random随机生成详解
- Python装饰器由浅入深
- python 引用,地址问题,可变类型和不可变类型
- 《Python数据科学指南》——1.22 列表排序
- 《像计算机科学家一样思考Python》——3.6 定义和使用
- 【21天学习经典算法】列表的分类与顺序查找(附Python完整代码)
- python学习之把列表元素拼接成字符串的4种方法
- Python迭代和解析(1):列表解析
- Python数据处理Tips机器学习中文数据8种常用处理方法
- Python项目列表
- Python基础入门-列表
- Python更新列表
- [Python]列表操作:将一个大列表拆分成若干个指定长度的小列表
- 【python】经典题型:list列表添加元素