python 随机选取列表中的元素
2021/7/29 9:06:09
本文主要是介绍python 随机选取列表中的元素,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
使用random模块中的sample函数
功能:
random.sample(seq, k)实现从序列或集合seq中随机选取k个独立的的元素
参数:
seq:元组、列表或字符串
k:选取元素个数
实例:
In [1]: import random
In [2]: f = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [3]: f
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [4]: random.sample(f, 5)
Out[4]: [5, 3, 6, 9, 4]
使用random模块中的choice函数
功能:
random.choice(seq)实现从序列或集合seq中随机选取一个元素
参数:
seq:元组、列表或字符串
实例:
In [1]: import random
In [2]: f = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [3]: f
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [4]: random.choice(f)
Out[4]: 2
这篇关于python 随机选取列表中的元素的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python