random模块

首先random函数并不是一个真正的随机数,而是根据随机数算法算出来的数

random 函数返回一个从 0.0 到 1.0 的随机浮点数 (包括 0.0, 但是不包括 1.0)。每次,调用 random,就会的到一个随机数。

  1. >>> import random 
  2. >>> random.random() 
  3. 0.9536935859948081 
  4. >>> random.random() 
  5. 0.40421571099356646 

randint 函数接受一个 low 和 high 参数,返回 low 和 high 之间的一个整数 (包括两者)。

  1. >>> random.randint(5, 10
  2. 5 
  3. >>> random.randint(5, 10
  4. 9 

随机选取0到100间的偶数

    >>> import random
    >>> random.randrange(0, 101, 2)
    42

要想随机地从一个序列中选取元素,可以使用 choice:

>>> t = [1, 2, 3]
>>> random.choice(t)
2

把原有的顺序打乱,按照随机顺序排列

  1. >>> import random 
  2. >>> items = [1, 2, 3, 4, 5, 6
  3. >>> random.shuffle(items) 
  4. >>> items 
  5. [3, 2, 5, 6, 4, 1
原文地址:https://www.cnblogs.com/ruhai/p/6607826.html