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

>>> 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章