python random.choice()方法,获取指定随机数

random.choice()方法

python的random模块中的choice()方法,可以从参数指定的序列中随机获取一个数。


参数

python序列,可以是列表list、元组tuple、字符串str等可通过索引来获取元素值的对象,比如因为set无法通过索引的方式来获取元素(set是无序的),所以集合set不能作为参数传递给random.choice()方法,否则python抛出TypeError。

提示:如果参数序列为空,python将抛出IndexError。


返回值

参数指定的序列中的某一个元素值。


random.choice()实例代码

>>> import random
>>> list1 = [2,1,3,5,7,6]
>>> random.choice(list1)
3
>>> tup = (2,3,5,7,6,8)
>>> random.choice(tup)
3
>>> set1 = {5,7,6,8,9,3}
>>> random.choice(set1) #参数为无序集合set,不能通过索引来获取值,python抛出TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda3/lib/python3.7/random.py", line 262, in choice
    return seq[i]
TypeError: 'set' object is not subscriptable
>>> str1 = "bacdeksj"
>>> random.choice(str1)
'e'
>>> range1 = range(1,6)
>>> random.choice(range1)
3
>>> list2 = []
>>> random.choice(list2) #参数为空的列表,python抛出IndexError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda3/lib/python3.7/random.py", line 261, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

全栈后端 / Python库 :









Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.