在 Python 中生成随机数列表
    
    
            Najwa Riyaz
    2023年1月30日
    
    Python
    Python Random
    
- 
          
            在 Python 中使用 random.sample()函数生成随机整数
- 
          
            在 Python 中使用 random.randint()函数生成随机整数
- 
          
            在 Python 中使用 numpy.random.randint()函数生成随机整数
- 
          
            在 Python 中使用 numpy.random.uniform()函数生成随机浮点数
 
本文介绍了在 Python 中生成随机数列表时可以遵循的不同方法。参考下面的这个列表。
在 Python 中使用 random.sample() 函数生成随机整数
    
使用 random.sample() 函数在 Python 中生成随机数。结果是一个包含随机数的 Python List。参考下面的语法。
random.sample(population_sequence, total_count_of_random_numbers)
生成的随机数总数为 total_count_of_random_numbers。参考下面的这个例子。
import random
random_numbers = random.sample(range(6), 3)
print(random_numbers)
type(random_numbers)
这里,生成了 0 到 6 之间的数字范围内的 3 个数字。
输出:
[3, 0, 1]
list
在 Python 中使用 random.randint() 函数生成随机整数
使用 random.randint() 函数使用列表推导在 Python 中生成随机数。结果是一个包含随机数的 Python 列表。语法如下。
random_numbers = [random.randint( < min_value > , < min_value > ) for x in range(total_count_of_random_numbers)]
这里有一个例子。
import random
random_numbers = [random.randint(0, 6) for x in range(3)]
print(random_numbers)
这里,生成了 0 到 6 之间的数字范围内的 3 个数字。
输出:
[1, 6, 6]
在 Python 中使用 numpy.random.randint() 函数生成随机整数
使用 numpy.random.randint() 函数生成随机整数。结果是一个包含随机数的 Python 列表。为此,我们首先导入 NumPy 库。你可以使用此语法。
np.random.randint(low=min_val, high=max_val, size=count).tolist()
以这个代码片段为例。
import numpy as np
random_numbers = np.random.randint(low=0, high=6, size=3).tolist()
print(random_numbers)
这里,生成了 0 到 6 之间的数字范围内的 3 个数字。
输出:
[2, 4, 2]
在 Python 中使用 numpy.random.uniform() 函数生成随机浮点数
使用 numpy.random.uniform 在 Python 中生成随机浮点数。
首先,导入 NumPy 库以使用该函数。语法如下。
random.uniform(low=minvalue, high=maxvalue, size=count_of_numbers)
按照这个例子。
import numpy
random_numbers = numpy.random.uniform(low=0, high=6, size=10).tolist()
print(random_numbers)
这里生成了 10 个浮点数,范围从 0 到 6。
输出:
[0.3077335256902074,
 4.305975943414238,
 4.487914411717991,
 1.141532770555624,
 2.849062698503963,
 3.7662017493968922,
 2.822739788956107,
 4.5291155985333065,
 3.5138714366365296,
 3.7069530642450745]
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe