Python random - zhongjiajie/zhongjiajie.github.com GitHub Wiki

python-random

random并非真的随机,他是一个确定值,由传输给random.seed()的值决定,只要seed值确定,所有的序列的值都是确定的.如果没有指定seed值默认传输当前unixtimestamp给seed,保证其随机.

random.seed

The method seed([x]) sets the integer starting value used in generating random numbers. Call this function before calling any other random module function.

  • parameters: x − This is the seed for the next random number. If omitted, then it takes system time to generate next random number.
  • return: no return.

random-seed-what-does-it-do:设定了seed,随机数生成序列都会确定,如果不提供会议当前时间为seed(保证了每次都是不用的random值)

import random
random.seed(3)  # set seed before other random method
print "Random number with seed 3 : ", random.random() # will generate a random number
# if you want to use the same random number once again in your program
random.seed(3)
random.random()   # same random number as before

# run bolow programme multiple times, it will get you same result
# 所以不仅仅是对下一个数,或者下一次操作有效,对全部相同的操作得到的结果都是一样的
# 可以理解为定义了`seed`之后,使用相同的 [函数, 次数] 得到的值是相同的
import random
random.seed(10)
for i in range(5):
    print(random.randint(1,100))

why need generate same random sequence

May be it is worth mentioning that sometimes we want to give seed so that same random sequence is generated on every run of the program. Sometimes, randomness in software program(s) is avoided to keep program behavior deterministic and possibility of reproducing the issues / bugs.

random.choice

从非空列表中随机抽取一个元素

from random import choice
choice(sequence)

shuffle

shuffle(x, random=None)Shuffle list x in place, and return None.没有返回值,同样没有返回值的是list.sorted()方法


⚠️ **GitHub.com Fallback** ⚠️