例如,如果我有一个范围从 0 到 9 的列表。我将如何使用 random.seed 函数从该数字范围中随机选择?还有我如何定义结果的长度。
import random
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = 10
random.seed(a)
length = 4
# somehow generate random l using the random.seed() and the length.
random_l = [2, 6, 1, 8]
例如,如果我有一个范围从 0 到 9 的列表。我将如何使用 random.seed 函数从该数字范围中随机选择?还有我如何定义结果的长度。
import random
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = 10
random.seed(a)
length = 4
# somehow generate random l using the random.seed() and the length.
random_l = [2, 6, 1, 8]
使用random.sample
. 它适用于任何序列:
>>> random.sample([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
[4, 2, 9, 0]
>>> random.sample('even strings work', 4)
['n', 't', ' ', 'r']
与random
模块中的所有函数一样,您可以像往常一样定义种子:
>>> import random
>>> lst = list(range(10))
>>> random.seed('just some random seed') # set the seed
>>> random.sample(lst, 4)
[6, 7, 2, 1]
>>> random.sample(lst, 4)
[6, 3, 1, 0]
>>> random.seed('just some random seed') # use the same seed again
>>> random.sample(lst, 4)
[6, 7, 2, 1]
>>> random.sample(lst, 4)
[6, 3, 1, 0]
import random
list = [] # your list of numbers that range from 0 -9
# this seed will always give you the same pattern of random numbers.
random.seed(12) # I randomly picked a seed here;
# repeat this as many times you need to pick from your list
index = random.randint(0,len(list))
random_value_from_list = list[index]
如果您numpy
已加载,则可以使用np.random.permutation
. 如果你给它一个整数作为参数,它会返回一个包含来自的元素的混洗数组np.arange(x)
,如果你给它一个类似对象的列表,则元素会被混洗,如果是numpy
数组,则复制数组。
>>> import numpy as np
>>> np.random.permutation(10)
array([6, 8, 1, 2, 7, 5, 3, 9, 0, 4])
>>> i = list(range(10))
>>> np.random.permutation(i)
array([0, 7, 3, 8, 6, 5, 2, 4, 1, 9])