简体   繁体   English

python列表中的随机序列

[英]python random sequence from list

If I had a list that ranged from 0 - 9 for example. 例如,如果我有一个范围从0-9的列表。 How would I use the random.seed function to get a random selection from that range of numbers? 我将如何使用random.seed函数从该范围的数字中进行随机选择? Also how I define the length of the results. 还有我如何定义结果的长度。

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]

Use random.sample . 使用random.sample It works on any sequence: 它适用于任何序列:

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

As with all functions within the random module, you can define the seed just as you normally would: 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]

If you got numpy loaded, you can use np.random.permutation . 如果加载了numpy ,则可以使用np.random.permutation If you give it a single integer as argument it returns a shuffled array with the elements from np.arange(x) , if you give it a list like object the elements are shuffled, in case of numpy arrays, the arrays are copied. 如果您给它一个整数作为参数,它将返回带有np.arange(x)元素的混洗数组,如果给它一个像object一样的列表,元素将被混洗,如果是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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM