Python 如何从给定范围生成固定长度值的随机列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3559337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a random list of fixed length of values from given range?
提问by user63503
How to generate a random (but unique and sorted) list of a fixed given length out of numbers of a given range in Python?
如何从 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]
采纳答案by SilentGhost
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]
回答by Manoj Govindan
A combination of random.randrangeand list comprehension would work.
random.randrange和列表理解的组合会起作用。
import random
[random.randrange(1, 10) for _ in range(0, 4)]
回答by ChantOfSpirit
import random
def simplest(list_length):
core_items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(core_items)
return core_items[0:list_length]
def full_random(list_length):
core_items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
result = []
for i in range(list_length):
result.append(random.choice(core_items))
return result

