简单 Python 快乐之旅之:Python 基础语法之 random 模块的使用例子


顾名思义,random 模块用于在一个范围里随机选取某一项。该模块提供了很多函数用以模拟随机行为。
本文我们将学习到在不同场景下使用 random 模块的例子。

1. 生成一个随机数

在 Python 中要生成一个随机数,你需要导入 random 库并使用 randint 函数。randint 函数的语法如下:

import random
randomnumber = random.randint(minimum, maximum)

其中

  • [minimum, maximum] 是要产生随机整数的范围
  • randint() 函数返回一个整数

生成随机数主要应用于模拟均匀概率事件、赌博、统计抽样等场景。
接下来的例子中,我们会在范围 [10, 152] 中产生一个随机数字:

import random

# Python Example to Generate a Random Number
randomnumber = random.randint(10, 152)
print(randomnumber)

执行和输出:
产生一个随机数字.jpg
多次执行应该会分别输出不同的结果。

2. 生成一个指定长度的随机数

在进行接下来的实验之前,我们先来熟悉一下 Python 里 pow 函数以及自定义函数的定义。

2.1. pow 函数

pow 函数的定义是 pow(x, y[, z]),计算 xy 次方,如果 z 存在的话再对 z 取模,其结果等效于 pow(x, y) % z。

2.2. 函数的定义

Python 中函数跟变量一样,需要先定义,再调用。函数定义的语法如下:

def 函数名(参数1, 参数2, 参数3, ...):
	函数体
	return 返回的值

注意:

  • 函数的返回值可以是任意的数据类型
  • 函数可以有多个返回值,有多个返回值时,返回的类型是元组类型
  • 函数也可以没有返回值,不写 return 的时候,该函数默认返回值为 None
  • 函数执行到 return 时,就结束了当前的函数,return 后继续定义的的语句块无意义

2.3. 指定长度的随机数

在接下来的例子中,我们结合 pow 函数和自定义函数,使用 random 库的 randint 函数生成指定长度的随机数:

# Python – Generate a Random Number of Specific Length
def randN(N):
    min = pow(10, N - 1)
    max = pow(10, N)
    return random.randint(min, max - 1)

print(randN(5))
print(randN(7))
print(randN(4))
print(randN(8))

执行和输出:
生成一个指定长度的随机数.png
该示例中我们定义了一个函数,根据传入的参数,生成该参数所定义长度的一个随机数。

3. 生成一个指定长度的随机字符串

在进行接下来的实验之前,我们先来熟悉一下 Python 里 random 库的 choice 函数以及字符串属性函数 join。

3.1. random 库的 choice 函数

choice 函数返回给定列表或元组或字符串中的某一随机项,该函数的语法如下:

import random
random.choice(seq)

seq 可以是一个列表,或一个元组,或一个字符串(关于列表、元组和 set 区别请参考同系列博客《简单 Python 快乐之旅之:Python 基础语法之循环关键字的使用例子》)。
比如以下用法:

print "choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9])

将打印出列表 [1, 2, 3, 5, 9] 中的某一项,如 2

3.2. 字符串属性函数 join

join 函数用于将序列中的元素以指定的字符连接成一个新的字符串。
join 函数的用法如下:

str.join(seq)

seq 是要连接的元素序列。
比如以下用法:

str = '-'
seq = ('a', 'b', 'c')
print(str.join(seq))

上例中我们指定了一个字符 str,定义了一个元组 seq,最终使用 join 函数用 str 将元组提供的元素连接成了一个新的字符串。上述示例的打印结果是 a-b-c

3.3. 指定长度的随机字符串

在接下来的例子中,我们结合 join 函数和自定义函数,使用 random 库的 choice 函数生成指定长度的随机字符串。
这个例子相对来讲就没那么简单了,化繁为简,我们将其拆分成以下四步走。
步骤一:选择提取源
首先得选择合适的要从其中提取字符的字符组。string 库为我们提供了以下字符组:

  • string.ascii_letters
  • string.ascii_lowercase
  • string.ascii_uppercase
  • string.digits
  • string.hexdigits
  • string.octdigits
  • string.punctuation
  • string.printable
  • string.whitespace

Python 3.7.1 的 string 库对上述字符组的定义源代码如下:

"""A collection of string constants.

Public module variables:

whitespace -- a string containing all ASCII whitespace
ascii_lowercase -- a string containing all ASCII lowercase letters
ascii_uppercase -- a string containing all ASCII uppercase letters
ascii_letters -- a string containing all ASCII letters
digits -- a string containing all ASCII decimal digits
hexdigits -- a string containing all ASCII hexadecimal digits
octdigits -- a string containing all ASCII octal digits
punctuation -- a string containing all ASCII punctuation characters
printable -- a string containing all ASCII characters considered printable

"""

__all__ = ["ascii_letters", "ascii_lowercase", "ascii_uppercase", "capwords",
           "digits", "hexdigits", "octdigits", "printable", "punctuation",
           "whitespace", "Formatter", "Template"]

import _string

# Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace

无论是定义还是注释说明都已经很清晰明了了,我们这里不再进行过多说明。
步骤二:提取选定字符串或字符组中的某一项
我们使用 random.choice() 函数来完成这个事情:

random.choice(string.ascii_uppercase + string.digits)

步骤三:重复步骤二 N 次
N 应该是要生成的随机字符串的长度:

random.choice(string.ascii_uppercase + string.digits) for _ in range(N)

上例定义了一个 _ 变量,结合 for 循环和 range(N),表示 random.choice(string.ascii_uppercase + string.digits) 执行了 N 次,即取了 N 次随机数。
关于 Python 中 for 循环的使用(含结合 range(start, stop)),请参考同系列博客《简单 Python 快乐之旅之:Python 基础语法之循环关键字的使用例子》。
步骤四:将这 N 个字符连接成一个字符串
使用空字符将步骤三生成的 N 个字符进行连接:

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

好了,完整示例如下:

# Python – Generate Random String of Specific Length
def randStr(chars = string.ascii_uppercase + string.digits, N = 10):
    return ''.join(random.choice(chars) for _ in range(N))

# default length(=10) random string
print(randStr())
# random string of length 7
print(randStr(N=7))
# random string with characters picked from ascii_lowercase
print(randStr(chars=string.ascii_lowercase))
# random string with characters picked from 'abcdef123456'
print(randStr(chars='abcdef123456'))

执行和输出:
指定长度的随机字符串.png
最后贴上本文示例完整源代码:

import random
import string

# Python Example to Generate a Random Number
randomnumber = random.randint(10, 152)
print(randomnumber)

# Python – Generate a Random Number of Specific Length
def randN(N):
    min = pow(10, N - 1)
    max = pow(10, N)
    return random.randint(min, max - 1)

print(randN(5))
print(randN(7))
print(randN(4))
print(randN(8))

# Python – Generate Random String of Specific Length
def randStr(chars = string.ascii_uppercase + string.digits, N = 10):
    return ''.join(random.choice(chars) for _ in range(N))

# default length(=10) random string
print(randStr())
# random string of length 7
print(randStr(N=7))
# random string with characters picked from ascii_lowercase
print(randStr(chars=string.ascii_lowercase))
# random string with characters picked from 'abcdef123456'
print(randStr(chars='abcdef123456'))

参考资料

发布了273 篇原创文章 · 获赞 1324 · 访问量 649万+

猜你喜欢

转载自blog.csdn.net/defonds/article/details/89342212