Python 标准库:random

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 英文文档

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容