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?

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年3月5日 下午2:23
下一篇 2023年3月5日

相关推荐