English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
您可以使用随机模块在Python中生成随机数。
Python提供random了可以生成随机数的模块。
这些是伪随机数,因为生成的数字序列取决于种子。
如果种子值相同,则序列将相同。例如,如果使用2作为播种值,则将始终看到以下序列。
import random random.seed(2) print(random.random()) print(random.random()) print(random.random())
输出将始终遵循以下顺序:
0.9560342718892494 0.9478274870593494 0.05655136772680869
Not so casual, are you?Since this generator is completely deterministic, it should not be used for encryption purposes.
This is a list of functions defined in the random module, with a brief explanation of their functions.
Function | Description |
---|---|
seed(a=None, version=2) | Initialize the random number generator |
getstate() | Return an object capturing the current internal state of the generator |
setstate(state) | Restore the internal state of the generator |
getrandbits(k) | Return a Python integer with k random bits |
randrange(start, stop[, step]) | Return a random integer within the range |
randint(a, b) | Return a random integer between a and b |
choice(seq) | Return a random element from a non-empty sequence |
shuffle(seq) | Random sequence |
sample(population, k) | Return a list of ak unique elements selected from the filled sequence |
random() | Return a range of [0.0,1The next random floating-point number of the form .0) |
uniform(a, b) | Return a random floating-point number between a and b |
triangular(low, high, mode) | Return a random floating-point number between the lower and upper bounds, and specify the pattern within these boundaries |
betavariate(alpha, beta) | Beta distribution |
expovariate(lambd) | Exponential distribution |
gammavariate(alpha, beta) | Gamma distribution |
gauss(mu, sigma) | Gaussian distribution |
lognormvariate(mu, sigma) | Lognormal distribution |
normalvariate(mu, sigma) | Normal distribution |
vonmisesvariate(mu, kappa) | Von Mises distribution |
paretovariate(alpha) | Pareto distribution |
weibullvariate(alpha, beta) | Weibull distribution |