Warning小心:这个模块不可用作安全方面的防护,安全方面需要看 secrets
模块
以下代码摘自官网。
1. 基础功能:产生随机数
以下的产生随机数均为产生一个随机数;choice()
也是选一个。choice()
,sample()
限定k
值可以取一段数据。
>>>from random import *
>>> random() # Random float: 0.0 <= x < 1.0
0.37444887175646646
>>> uniform(2.5, 10.0) # Random float: 2.5 <= x < 10.0
3.1800146073117523
>>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
5.148957571865031
>>> randrange(10) # Integer from 0 to 9 inclusive
7
>>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
26
>>> choice(['win', 'lose', 'draw']) # Single random element from a sequence
'draw'
>>> deck = 'ace two three four'.split()
>>> shuffle(deck) # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']
>>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement
[40, 10, 50, 30]`
>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']
2. 模拟产生次数,计算概率
注意算出来的概率每次都不一样。
>>> # Deal 20 cards without replacement from a deck of 52 playing cards
>>> # and determine the proportion of cards with a ten-value
>>> # (a ten, jack, queen, or king).
>>> deck = collections.Counter(tens=16, low_cards=36)
>>> seen = sample(list(deck.elements()), k=20)
>>> seen.count('tens') / 20
0.15
3. 结合numpy模块使用
差不多,引入了数组功能。
参考资料:
- 为什么你用不好Numpy的random函数?
- 官网
https://docs.scipy.org/doc/numpy/reference/routines.random.html
参考资料:
- 官网 https://docs.python.org/3/library/random.html
- Capricorn的实验室 , Python中的random模块
- Python random模块
- 为什么你用不好Numpy的random函数?
2018.5.14