来自lis的python随机序列

2024-05-01 21:32:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个从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]

Tags: andthe函数import列表定义数字random
3条回答
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]

使用^{}。它可以按任何顺序工作:

>>> 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]

如果加载了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])

相关问题 更多 >