How to generate a random list of fixed length of v

2019-02-01 20:57发布

How to generate a random (but unique and sorted) list of a fixed given length out of numbers of a given range in Python?

Something like that:

>>> list_length = 4
>>> values_range = [1, 30]
>>> random_list(list_length, values_range)

[1, 6, 17, 29]

>>> random_list(list_length, values_range)

[5, 6, 22, 24]

>>> random_list(3, [0, 11])

[0, 7, 10]

2条回答
男人必须洒脱
2楼-- · 2019-02-01 21:36

A random sample like this returns list of unique items of sequence. Don't confuse this with random integers in the range.

>>> import random
>>> random.sample(range(30), 4)
[3, 1, 21, 19]
查看更多
别忘想泡老子
3楼-- · 2019-02-01 21:44

A combination of random.randrange and list comprehension would work.

import random
[random.randrange(1, 10) for _ in range(0, 4)]
查看更多
登录 后发表回答