📜  Python|在给定范围内生成随机数并存储在列表中

📅  最后修改于: 2022-05-13 01:55:16.198000             🧑  作者: Mango

Python|在给定范围内生成随机数并存储在列表中

给定下限和上限,在给定范围内生成给定计数的随机数,从“开始”到“结束”并将它们存储在列表中。
例子:

Input : num = 10, start = 20, end = 40
Output : [23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
The output contains 10 random numbers in
range [20, 40].

Input : num = 5, start = 10, end = 15
Output : [15, 11, 15, 12, 11]
The output contains 5 random numbers in
range [10, 15].

Python提供了一个随机模块来生成随机数。为了生成随机数,我们使用了 random函数和 randint函数。
句法:

randint(start, end)

randint 接受两个参数:起点和终点。两者都应该是整数,第一个值应该总是小于第二个。

Python3
# Python code to generate
# random numbers and
# append them to a list
import random
 
# Function to generate
# and append them
# start = starting range,
# end = ending range
# num = number of
# elements needs to be appended
def Rand(start, end, num):
    res = []
 
    for j in range(num):
        res.append(random.randint(start, end))
 
    return res
 
# Driver Code
num = 10
start = 20
end = 40
print(Rand(start, end, num))


Python3
# Python code to generate
# random numbers and
# append them to a list
import numpy as np
def Rand(start, end, num):
    res = []
 
    for j in range(num):
        res.append(np.random.randint(start, end))
 
    return res
 
 
# Driver Code
num = 10
start = 20
end = 40
print(Rand(start, end, num))


输出:

[23, 20, 30, 33, 30, 36, 37, 27, 28, 38]

方法2:使用numpy random.randint() 方法生成随机数。

Python3

# Python code to generate
# random numbers and
# append them to a list
import numpy as np
def Rand(start, end, num):
    res = []
 
    for j in range(num):
        res.append(np.random.randint(start, end))
 
    return res
 
 
# Driver Code
num = 10
start = 20
end = 40
print(Rand(start, end, num))

输出:

[30, 30, 38, 39, 39, 37, 24, 25, 28, 32]