random应用及常见用法

应用

生成一个8个字符的字母数字密码

>>> import string
>>> alphabet = string.ascii_letters + string.digits
>>> alphabet
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
>>> password = "".join(choice(alphabet) for i in range(8))
>>> password
'xV1c31LL'

生成包含至少一个小写字符、至少一个大写字符和至少三个数字的10个字符的字母数字密码

>>> import string
>>> alphabet = string.ascii_letters + string.digits
>>> while True:
...     password = ''.join(choice(alphabet) for i in range(10))
...     if (any(c.islower() for c in password)
...             and any(c.isupper() for c in password)
...             and sum(c.isdigit() for c in password) >= 3):
...         break
... 
>>> password
'ZnC262xNrt'
>>> 
>>> (c.islower() for c in password)
<generator object <genexpr> at 0x7fc3f9af7728>
>>> [c.islower() for c in password]
[False, True, False, False, False, False, True, False, True, True]

补:any() 与 all() 的用法

any: 至少有一个为真,那么结果为真
all: 所有为真,结果才为真

>>> any("")
False
>>> any(" ")
True
>>> any("abc0")
True
>>> any("0")
True
>>> any([0,1])
True
>>> any([0])
False
>>> any([])
False

>>> all("")		# 居然为真,注意了
True
>>> all(" ")
True
>>> all("1231230")
True

>>> all([1,2,0])
False
>>> all([""])
False
>>> all([" "])
True
>>> all([])		# 居然为真,注意了
True

常见用法

>>> from random import random, uniform, expovariate, randrange, choice, shuffle, sample
>>> random()			# Random float:  0.0 <= x < 1.0
0.793257329955433
>>> uniform(2.5, 10.0)	# Random float:  2.5 <= x < 10.0
6.579550961453425
>>> expovariate(1/5)	# Interval between arrivals averaging 5 seconds
0.3419791175487244
>>> randrange(10)	 	# Integer from 0 to 9 inclusive
8
>>> randrange(0, 101, 2)	# Even integer from 0 to 100 inclusive
50
>>> choice(["win", "lose", "draw"])		# Single random element from a sequence
'lose'
>>> deck = "ace two three four".split()
>>> deck
['ace', 'two', 'three', 'four']
>>> shuffle(deck)		# Shuffle a list
>>> deck
['ace', 'four', 'three', 'two']
>>> sample(deck, k=2)		# Four samples without replacement
['three', 'four']
>>> deck
['ace', 'four', 'three', 'two']

参考:

  1. https://docs.python.org/3/library/random.html#random.SystemRandom
  2. https://docs.python.org/3/library/secrets.html?highlight=choice#module-secrets
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值