[英]how to random 10 numbers between 1 and 5 in list and the list must inculde all number
from random import randint
k=[]
for i in range(10):
k.append(randint(1,5))
k.sort()
print(k)
The output will be correct but sometimes it not include value from 1 to 5. for example, maybe k=[2,3,3,3,3,4,4,5,5,5] and not included 1. I need to include all numbers output 是正确的,但有时它不包括从 1 到 5 的值。例如,可能 k=[2,3,3,3,3,4,4,5,5,5] 并且不包括 1。我需要包括所有数字
10 random numbers between 1 and 5 means a list of [1,1,1,1,1,1,1,1,1,1]
is a valid result - it is just very unlikely. 1 到 5 之间的 10 个随机数意味着[1,1,1,1,1,1,1,1,1,1]
的列表是有效的结果 - 这是非常不可能的。
If you need to ensure 1 to 5 are in it, start with [1,2,3,4,5]
and add 5 random numbers:如果您需要确保其中有 1 到 5,请从[1,2,3,4,5]
开始并添加 5 个随机数:
from random import choices
k = [1,2,3,4,5]
k.extend( choices(range(1,6), k=5)) # add 5 more random numbers
k.sort()
print(k)
to get要得到
[1,1,2,2,3,4,4,5,5,5] # etc.
The part choices(range(1,6), k=5)
returns a list of 5 numbers in the range 1-5 without need for a loop.部分choices(range(1,6), k=5)
返回范围为1-5的5个数字的列表,无需循环。
Using NumPy library could have priority over pythonic random to work with to do so;使用NumPy库可以优先于 pythonic random使用这样做; which may be very faster in huge data volumes :在大量数据中这可能会更快:
import numpy as np
nums = np.arange(1, 6) # create integer numbers from 1 to (6 - 1) to ensure 1 to 5 will be contained
ran = np.random.random_integers(1, 6, 5) # create 5 random integers from 1 to (6 - 1)
combine = np.concatenate((nums, ran)) # combining aforementioned two arrays together
np.random.shuffle(combine) # shuffling the created combined array
which will get arrays like [4 5 4 2 5 1 3 4 2 1]
, which will contain all integers from 1 to 5. This array can be converted to list by combine.tolist()
.这将得到 arrays 像[4 5 4 2 5 1 3 4 2 1]
,它将包含从 1 到 5 的所有整数。这个数组可以通过combine.tolist()
转换为列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.