Python 标准库:random

简介: 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']




目录
相关文章
|
24天前
|
存储 人工智能 测试技术
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
本文介绍如何使用LangChain结合DeepSeek实现多轮对话,测开人员可借此自动生成测试用例,提升自动化测试效率。
227 125
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
|
16天前
|
监控 数据可视化 数据挖掘
Python Rich库使用指南:打造更美观的命令行应用
Rich库是Python的终端美化利器,支持彩色文本、智能表格、动态进度条和语法高亮,大幅提升命令行应用的可视化效果与用户体验。
70 0
|
3月前
|
存储 Web App开发 前端开发
Python + Requests库爬取动态Ajax分页数据
Python + Requests库爬取动态Ajax分页数据
|
6月前
|
JavaScript 前端开发 Java
通义灵码 Rules 库合集来了,覆盖Java、TypeScript、Python、Go、JavaScript 等
通义灵码新上的外挂 Project Rules 获得了开发者的一致好评:最小成本适配我的开发风格、相当把团队经验沉淀下来,是个很好功能……
1167 103
|
2月前
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
121 18
|
3月前
|
JSON 网络安全 数据格式
Python网络请求库requests使用详述
总结来说,`requests`库非常适用于需要快速、简易、可靠进行HTTP请求的应用场景,它的简洁性让开发者避免繁琐的网络代码而专注于交互逻辑本身。通过上述方式,你可以利用 `requests`处理大部分常见的HTTP请求需求。
314 51
|
2月前
|
机器学习/深度学习 API 异构计算
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
JAX是Google开发的高性能数值计算库,旨在解决NumPy在现代计算需求下的局限性。它不仅兼容NumPy的API,还引入了自动微分、GPU/TPU加速和即时编译(JIT)等关键功能,显著提升了计算效率。JAX适用于机器学习、科学模拟等需要大规模计算和梯度优化的场景,为Python在高性能计算领域开辟了新路径。
181 0
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
|
2月前
|
数据采集 存储 Web App开发
Python爬虫库性能与选型实战指南:从需求到落地的全链路解析
本文深入解析Python爬虫库的性能与选型策略,涵盖需求分析、技术评估与实战案例,助你构建高效稳定的数据采集系统。
254 0
|
2月前
|
存储 监控 安全
Python剪贴板监控实战:clipboard-monitor库的深度解析与扩展应用
本文介绍了基于Python的剪贴板监控技术,结合clipboard-monitor库实现高效、安全的数据追踪。内容涵盖技术选型、核心功能开发、性能优化及实战应用,适用于安全审计、自动化办公等场景,助力提升数据管理效率与安全性。
107 0

热门文章

最新文章

推荐镜像

更多