Python 中的 random 模块用于生成各种分布的随机数。random 模块可以生成随机浮点数、整数、字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据等。
在 Python 中,实现我们比较熟悉的均匀分布、正态(高斯)分布都非常方便,此外,还有对数正态、负指数、伽马和 β 分布的函数。
几乎所有模块函数都依赖于基本函数random(),在 [0.0,1.0) 中均匀地生成随机浮点。Python 使用 Mersenne Twister 作为核心生成器。它产生 53 位精确度浮点数,周期为2 ** 19937-1。底层使用 C 实现既快又线程安全。Mersenne Twister 是现存最广泛测试的随机数生成器之一。然而,它不适合于所有目的,比如不适合于加密用途。
警告:该模块的伪随机生成器不应该用于安全目的。
1. random.random
函数是这个模块中最常用的方法了,它会生成一个随机的浮点数,范围是在 0.0~1.0 之间。
2. random.uniform
它可以设定浮点数的范围,一个是上限,一个是下限。random.uniform 的函数原型为:random.uniform(a, b),用于生成一个指定范围内的随机符点数,两个参数其中一个较大的数是上限,较小的数是下限。
>>> import random
>>> print(random.uniform(10, 20))
12.2990031101
>>> print(random.uniform(20,10))
13.597102709
3. random.sample
可以从指定的序列中,随机地选择元素得到指定长度的列表,不修改原先的序列。random.sample 的函数原型为:random.sample(sequence, k),其中的两个参数一个为序列,另一个为新序列的长度。
import random
orig_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slice_list = random.sample(orig_list, 5)
print(orig_list)
print(slice_list)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[4, 3, 2, 8, 6]
4. random.choice
random.choice 从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数 sequence 表示一个有序类型, 它在 python 中不是一种特定的类型,而是泛指一系列的类型。列表、元组、字符串都属于 sequence。下面是使用 choice 的一些例子:
>>> print(random.choice("学习Python"))
学
>>> print(random.choice(["oatmeal","is","a","cute","man"]))
is
>>> print(random.choice(("Tuple","List","Dict")))
Tuple
>>>
然后我们再来个实际点的例子,比如你要帮领导写个发言稿, 你先收集好领导平时经常用的词或者语句, 用 random.choice 从这些语句中随机的选择拼接,这样就不用费脑筋就可以完成一篇文章了, 当然写出来后还得通顺通顺。
import random
import textwrap
OPENING_WORDS = ['Our', 'clear', 'strategic', 'direction', 'is', 'to', 'invoke',]
PHRASE_TABLE = (
("accountable", "transition", "leadership"),
("driving", "strategy", "implementation"),
("drilling down into", "active", "core business objectives"),
("next billion", "execution", "with our friends in <other corp.>"),
("creating", "next-generation", "franchise platform"),
("<big corp.>'s", "volume and", "value leadership"),
("significant", "end-user", "experience"),
("transition", "from <small corp.>", "to <other corp.>'s platform"),
("integrating", "shared", "services"),
("empowered to", "improve and expand", "our portfolio of experience"),
("deliver", "new", "innovation"),
("ramping up", "diverse", "collaboration"),
("next generation", "mobile", "ecosystem"),
("focus on", "growth and", "consumer delight"),
("management", "planning", "interlocks"),
("necessary", "operative", "capabilities"),
("knowledge", "optimization", "initiatives"),
("modular", "integration", "environment"),
("software", "creation", "processes"),
("agile", "working", "practices"),
)
INSERTS = ('for', 'with', 'and', 'as well as', 'by',
'whilst not forgetting',
'. Of course',
'. To be absolutely clear',
'. We need',
'and unrelenting',
'with unstoppable',
)
def get_phrase():
"""Return a phrase by choosing words at random from each column of the PHRASE_TABLE."""
return [random.choice(PHRASE_TABLE)[i] for i in range(3)]
def get_insert():
"""Return a randomly chosen set of words to insert between phrases."""
return random.choice(INSERTS)
def write_speech(n):
"""Write a speech with the opening words followed by n random phrases
interspersed with random inserts."""
phrases = OPENING_WORDS
for i in range(n):
phrases.extend(get_phrase())
if i != n-1:
phrases.append(get_insert())
text = ' '.join(phrases) + '.'
print(textwrap.fill(text))
if __name__ == '__main__':
write_speech(8)
开始这篇文章可以有个固定的开头,把这些词存在 OPENING_WORDS
列表里。常用的语句放在 PHRASE_TABLE
元组里, 把它写成三列的形式, 每次从这三列里各选一个词组成一个新的语句。 然后还得从 INSERTS
里面选一个连接词。
在从 PHRASE_TABLE
选择词汇的时候使用了 [random.choice(PHRASE_TABLE)[i] for i in range(3)]
语句, 注意random.choice
在这一句被执行了三次,每一次随机的选择表里面的某一行的元组,然后把元组中对应列的词汇找出来。
输出:
Our clear strategic direction is to invoke next generation planning
collaboration and unrelenting next billion shared experience for
accountable mobile innovation for driving shared with our friends in
<other corp.> with unstoppable focus on mobile initiatives . Of course
significant execution capabilities and unrelenting ramping up
integration innovation and unrelenting focus on execution ecosystem.
5. random.randrange
random.randrange(stop)
random.randrange(start, stop[, step])
从 range(start, stop, step) 返回一个 start 到 end 范围内的随机整数(start,end,step 都是整数,不包含 end),可以指定 step。
下面我们利用 randrange 实现一个 21 点扑克牌游戏。
import random
def ask_user(prompt, response1, response2):
"""
Ask user for a response in two responses.
prompt (str) - The prompt to print to the user
response1 (str) - One possible response that the user can give
response2 (str) - Another possible response that the user can give
"""
while True:
# ask user for response
user_response = input(prompt)
#if response is response1 or response2 then return
if user_response == response1 or user_response == response2:
return user_response
def print_card(name, num):
"""
print "______ draws a _____" with the first blank replaced by the user's
name and the second blank replaced by the value given to the function.
name (str) - the user name to print out
num (int) - the number to print out
"""
# if the value is a 1, 11, 12, 13, print Ace, Jack, Queen, King
if num == 1:
num = "Ace"
elif num == 11:
num = "Jack"
elif num == 12:
num = "Queen"
elif num == 13:
num = "King"
else:
num = str(num)
# print the string
print(name, "draws a", num)
def get_ace_value():
"""
Ask the user if they want to use a 1 or 11 as their Ace value.
"""
# get the value use "ask_user" function
value = ask_user("Should the Ace be 1 or 11?", "1", "11")
# retrun the value
return int(value)
def deal_card(name):
"""
Pick a random number between 1 and 13, and print out what the user drew.
name (str) - the user name to print out
"""
# get a random number in range 1 to 13
num = random.randrange(1, 13+1)
# use "print_card" function to print out what the user drew
print_card(name, num)
if num > 10:
# if the card is a Jack, Queen, or King, the point-value is 10
return 10
elif num == 1:
# If the card is an Ace, ask the user if the value should be 1 or 11
return get_ace_value()
else:
return num
def adjust_for_bust(num):
"""
If the given number is greater than 21, print "Bust!" and return -1.
Otherwise return the number that was passed in.
num (int) - the given number
"""
# determine the value of num
if num > 21:
print("Bust!")
return -1
else:
return num
def hit_or_stay(num):
"""
Prompt the user hit or stay and return user's chose.
num (int) - the value of a player's card hand
"""
if num <= 21:
chose = ask_user("Hit or stay?", "hit", "stay")
# if num less than 21 and user chose hit return True
if chose == "hit":
return True
# otherwise return False
return False
def play_turn(name):
"""
Play whole the trun for a user.
name (str) - the player's name
"""
# print out that it's the current players turn
print("==========[ Current player:", name, "]==========")
# set total score zero
total_score = 0
# deal the player a card for loop
while True:
# get total score
total_score += deal_card(name)
# if not busted print out the player's total score
print("Total:", total_score)
# if player chose stay return the result, otherwise continue the loop
if not hit_or_stay(total_score):
return adjust_for_bust(total_score)
def determine_winner(name1, name2, score1, score2):
"""
Determine_the game's winner.
name1 (str) - the first player's name
name2 (str) - the second player's name
score1 (str) - the first player's score
score2 (str) - the second player's score
"""
if score1 == score2:
print(name1, "and", name2, "tie!")
elif score1 > score2:
print(name1, "wins!")
elif score1 < score2:
print(name2, "wins!")
def main():
"""
The main program of BlackJack game
"""
while True:
# Ask each player for their name
name1 = input("Player 1 name:")
name2 = input("Player 2 name:")
# Greet them
print("Welcome to BlackJack", name1, "and", name2)
print()
# Let the first player play a turn
score1 = play_turn(name1)
print()
# Let the second player play a turn
score2 = play_turn(name2)
print()
# Determine who won
determine_winner(name1, name2, score1, score2)
# Play again if they say yes and end the loop if they say no
if ask_user("Would you like to play again?", "yes", "no") == "no":
break
if __name__ == "__main__":
main()
输出:
Player 1 name:oatmeal
Player 2 name:alice
Welcome to BlackJack oatmeal and alice
==========[ Current player: oatmeal ]==========
oatmeal draws a 9
Total: 9
Hit or stay?hit
oatmeal draws a 3
Total: 12
Hit or stay?hit
oatmeal draws a 2
Total: 14
Hit or stay?stay
==========[ Current player: alice ]==========
alice draws a 9
Total: 9
Hit or stay?hit
alice draws a Jack
Total: 19
Hit or stay?stay
alice wins!
Would you like to play again?yes
Player 1 name:oatmeal
Player 2 name:alice
Welcome to BlackJack oatmeal and alice
==========[ Current player: oatmeal ]==========
oatmeal draws a Ace
Should the Ace be 1 or 11?11
Total: 11
Hit or stay?hit
oatmeal draws a Jack
Total: 21
Hit or stay?stay
==========[ Current player: alice ]==========
alice draws a 9
Total: 9
Hit or stay?hit
alice draws a 2
Total: 11
Hit or stay?hit
alice draws a 6
Total: 17
Hit or stay?hit
alice draws a Ace
Should the Ace be 1 or 11?1
Total: 18
Hit or stay?hit
alice draws a 2
Total: 20
Hit or stay?stay
oatmeal wins!
6. random.randint
而 randint 是怎么用的呢,它可以从参数指定的范围里随机选择一个整数返回来。
import random
import time
def open_connection():
if random.randint(0, 3) != 0:
raise ValueError
return True
def connect(nretry=100):
for _ in range(nretry):
try:
if open_connection():
print("Connected!")
return
except ValueError:
print("failed to connect, note this!")
time.sleep(2)
continue
if "__main__" in __name__:
connect()
在这个程序里, 我们模拟了网络连接的情况。如果在连接的时候没有得到正常值,那就等一会儿,然后再连接。
输出:
failed to connect, note this!
failed to connect, note this!
Connected!
7. random.shuffle()
可以将一个列表里的元素打乱顺序重新排列。
import random
def remove_indices(mylist, idxs):
result = []
for i, l in enumerate(mylist):
if i not in idxs:
result.append(l)
return result
if "__main__" in __name__:
name_list = ["xiaopai", "oatmeal", "shuo", "gang"]
print(name_list)
random.shuffle(name_list)
idx_list = []
for i in range(2):
Num = input("please enter a number:")
idx_list.append(int(Num))
print(name_list)
win_names = remove_indices(name_list, idx_list)
print(win_names)
这个在抽签的时候尤其好用, 备选的人名组成一个列表,然后用 shuffle 把它打乱, 由人再输入些下标数值,让对应下标的人名从列表里被删掉,看看剩下的人是谁。
输出:
['xiaopai', 'oatmeal', 'shuo', 'gang']
please enter a number:1
please enter a number:2
['shuo', 'xiaopai', 'gang', 'oatmeal']
['shuo', 'oatmeal']
参考:
random 英文文档