How to create a random list with only unique values? [duplicate]

天涯浪子 提交于 2021-01-28 08:34:46

问题


I want to create a random list with 100 elements. So far, so good...

Example 1: works fine, because the function has a range which is big enough not to repeat any value

list = random.sample(range(1,200),100)

Example 2: Does not work, because the range is too small (sample is larger than population)

list = random.sample(range(50,80),100)

I am looking for a way to create that random list with more values than the range and it is no problem that the elements exists several times.


回答1:


In this case, do not use random.sample, but build the list from elements chosen within a range:

import random

[random.randrange(50, 80) for _ in range(100)]

example output:

[57,
 52,
 59,
 67,
 52,    # some elements repeat
 64,
 75,
...



回答2:


Use numpy random:

import numpy as np
np.random.randint(low=3,high=12,size=100)




回答3:


Have a look at numpy.choice

import numpy as np
l = range(50,80)
np.random.choice(l, 100, True)



回答4:


Use list comprehension + randint,

[random.randint(1,200) for _ in range(100)]

See the element are repeating the count is not 100,

In [6]: len(set([random.randint(1,200) for _ in range(100)]))
Out[6]: 76


来源:https://stackoverflow.com/questions/46969675/how-to-create-a-random-list-with-only-unique-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!