python中【random】函数用法、randint(a, b)、random( )、uniform(a, b)、shuffle(序列)、sample( )

您所在的位置:网站首页 randrange在python中的用法 python中【random】函数用法、randint(a, b)、random( )、uniform(a, b)、shuffle(序列)、sample( )

python中【random】函数用法、randint(a, b)、random( )、uniform(a, b)、shuffle(序列)、sample( )

2024-07-17 13:47| 来源: 网络整理| 查看: 265

1、random.randint(a, b)  —— 随机生成一个整数,范围在[a,b]之间 ——闭区间

即:生成指定范围内的整数。

注意:a、b必须是整数

import random a = random.randint(1, 3) # 从1~3里随机生成一个整数,包括1和3 print(a) # 结果: 1 或者2 或者 3

2、random.random( ) ——随机生成一个浮点数,范围在[0,1)之间 ——左闭右开

import random a = random.random() print(a) # 结果: 0.010555497939993108

3、random.uniform(a, b) ——随机生成一个浮点数,范围在[a,b)之间 ——左闭右开

import random a = random.uniform(1, 3) print(a) # 结果: 1.2921501572960141

4、random.shuffle(x) ——将一个列表中的元素打乱

import random x = [1, 2, 3, 4, 5] random.shuffle(x) # !!! print(x) # 结果: [1, 3, 5, 2, 4] 或者 [2, 1, 4, 5, 3] .....

再比如:利用range( )范围函数,生成列表

x = list(range(10)) # 生成列表:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(x) # 结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 现在把它打乱 x = list(range(10)) random.shuffle(x) print(x) # 结果: [4, 5, 9, 2, 8, 7, 1, 3, 0, 6] 或 [8, 9, 7, 2, 1, 6, 5, 0, 4, 3] ....

5、random.sample(序列, k) ——从指定序列中,随机获取指定长度k的片段

# 例1 import random x = [1, 3, 2, 5, 6] a = random.sample(x, 3) print(a) # 结果: [5, 2, 3] 或者[1, 6, 3] .... # 例2 a = random.sample(range(10), 3) print(a) # 结果: [3, 0, 5] 或者:[8, 6, 5] .....

sample( )函数不会修改原有序列。

import random x = [1, 3, 2, 5, 6] a = random.sample(x, 3) print(a) print("原来序列:", x) # 结果: [2, 5, 6] 原来序列: [1, 3, 2, 5, 6]



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3