Python random.choice() 方法用于从序列中选择一个随机项目。此序列可以是列表、元组、字符串或其他有序元素集合。其他序列(如 sets)不被接受为此方法的参数,并且会引发 TypeError。这是因为 sets 被视为无序序列,并且不会记录其中的元素位置。因此,它们不是可下脚本的。
choice() 方法在处理随机算法或程序时派上用场。
注意 − 这个函数不能直接访问,所以我们需要导入 random 模块,然后我们需要使用 random 静态对象调用这个函数。
语法
以下是 Python random.choice() 方法的语法 -
参数
seq − 这是元素(如列表、元组、字符串或字典)的有序集合。
返回值
此方法返回一个随机项。
示例 1
以下示例显示了 Python random.choice() 方法的用法。
当我们运行上述程序时,它会产生以下结果——
Random element in a given list 1
Random element in a given string u
Random element in a given tuple 8
Random element in a given dictionary b
Random element in a given string u
Random element in a given tuple 8
Random element in a given dictionary b
如果再次执行相同的程序,则结果与第一个输出不同 -
Random element in a given list 2
Random element in a given string t
Random element in a given tuple 0
Random element in a given dictionary d
Random element in a given string t
Random element in a given tuple 0
Random element in a given dictionary d
示例 2
此方法可用于使用 range() 函数在元素范围内选择元素。
在下面的示例中,通过将两个整数参数传递给 range() 函数来返回整数范围;这个范围作为参数传递给 choice() 方法。作为返回值,我们尝试从此范围中检索随机整数。
上述程序的输出如下 -
The random integer from the given range is: 14
示例 3
但是,如果我们创建其他序列对象(如 sets)并将其传递给 choice() 方法,则会引发 TypeError。
输出
Traceback (most recent call last):
File "main.py", line 5, in <module>
print("Random element in a given set", random.choice(s))
File "/usr/lib64/python3.8/random.py", line 291, in choice
return seq[i]
TypeError: 'set' object is not subscriptable
File "main.py", line 5, in <module>
print("Random element in a given set", random.choice(s))
File "/usr/lib64/python3.8/random.py", line 291, in choice
return seq[i]
TypeError: 'set' object is not subscriptable
示例 4
当我们将空序列作为参数传递给方法时,会引发 IndexError。
输出
Traceback (most recent call last):
File "main.py", line 7, in <module>
item = random.choice(seq)
File "/usr/lib64/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
File "main.py", line 7, in <module>
item = random.choice(seq)
File "/usr/lib64/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence