python—从list中随机抽取元素

1、随机抽取一个元素

from random import choice

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(choice(l))

choice(seq): Choose a random element from a non-empty sequence

2、随机抽取若干个元素(无重复)

from random import sample

l = [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.

3、随机抽取若干个元素(有重复)

import numpy as np

l = [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) to high (exclusive).

4、numpy.random.choice

numpy.random.choice(a, size=None, replace=True, p=None): 从一维 数组 a 中选出 size 个元素,a中每个元素被选中的概率由一维数组p定义

replace=True: 可以从a 中反复选取同一个元素

replace=False: a 中同一个元素只能被选取一次

import numpy as np

array = 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]
'''

参考

1、python技巧——从list中随机抽取元素的方法

2、What does replacement mean in numpy.random.choice?

  • 15
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值