列表中的python随机序列

时间:2013-03-07 20:55:52

标签: 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]

3 个答案:

答案 0 :(得分:9)

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

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

答案 2 :(得分: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])