欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

random应用及常见用法

程序员文章站 2024-03-19 11:03:28
...

应用

生成一个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

>>> if d:
...     print("true")
... 
>>> if all(d):
...     print("true")
... 
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
相关标签: random