Python Basic - Random Module (随机数模块)

random 模块简介

用于生成随机数,可按照一定的规则生成指定范围内的随机数,如后续示例所示

示例一:random.random()

import random
print(random.random())
print(random.random())
print(random.random())
print(random.random())
"""
0.7549817872782207
0.8463429995114858
0.5849971147917522
0.8639473485804318
"""

默认是随机输出1以内的小数

示例二:random.randint()----指定范围内随机整数

import random
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
"""
9
9
7
7
1
5
3
4
4
7
"""

示例三:random.choice()–从一个序列中随机选择一个

import random
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice(["Elom Mask","Tesla",["Space X","Rocket"]]))
"""
E
k
s
E
M
s
n
Tesla
"""

random.shuffle()

将顺序打乱,再随机排序

Help on method shuffle in module random:

shuffle(x, random=None) method of random.Random instance
    Shuffle list x in place, and return None.
    
    Optional argument random is a 0-argument function returning a
    random float in [0.0, 1.0); if it is the default None, the
    standard random.random will be used.

None

random.sample()–随机选取指定数量的元素

import random
print(random.sample(["Elom Mask","Tesla",["Space X","Rocket"]],2))
print(random.sample(["Elom Mask","Tesla",["Space X","Rocket"]],2))
"""
['Tesla', ['Space X', 'Rocket']]
['Tesla', 'Elom Mask']
"""

random.randrange()–指定范围内随机,不包含最右侧

import random
print(random.randrange(1,8))
"""
5
"""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值