Python 官方文档:入门教程 => 点击学习
1、随机抽取一个元素 from random import choicel = [1, 2, 3, 4, 5, 6, 7, 8, 9]print(choice(l)) choice(seq): C
from random import choicel = [1, 2, 3, 4, 5, 6, 7, 8, 9]print(choice(l))
choice(seq): Choose a random element from a non-empty sequence
from random import samplel = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]print(sample(l, 5)) # 随机抽取5个元素'''[5, 10, 1, 4, 2]'''
sample(seq): Chooses k unique random elements from a population sequence or set.
import numpy as npl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]index = np.random.randint(0, len(l), size=5)print([l[i] for i in index])'''[9, 9, 4, 3, 4]'''
randint(low, high=None, size=None): Return random integers from
low
(inclusive) tohigh
(exclusive).
numpy.random.choice(a, size=None, replace=True, p=None): 从一维 数组
a
中选出size
个元素,a
中每个元素被选中的概率由一维数组p
定义
replace=True
: 可以从a
中反复选取同一个元素
replace=False
:a
中同一个元素只能被选取一次
import numpy as nparray = list(range(10))repeat = np.random.choice(array, size=5, replace=True)print(f"replace=True的情况:{repeat}")no_repeat = np.random.choice(array, size=5, replace=False)print(f"replace=False的情况:{no_repeat}")'''replace=True的情况:[6 2 9 1 6]replace=False的情况:[1 4 7 2 0]'''
--结束END--
本文标题: python—从list中随机抽取元素
本文链接: https://www.lsjlt.com/news/433160.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0