Python3 choice()函数

choice() 方法从列表,元组或字符串中返回一个随机的项目。

语法

以下是 choice() 方法的语法:
choice( seq )

注:此函数无法直接访问,所以我们需要导入 random 模块,然后用数学静态对象调用这个函数。 

参数

  • seq -- 这可以是一个列表,元组或字符串...

返回值

此方法返回一个随机的项目。

示例

下面的例子显示 choice() 方法的使用。
#!/usr/bin/python3
import random

print ("returns a random number from range(100) : ",random.choice(range(100)))
print ("returns random element from list [1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9]))
print ("returns random character from string 'Hello World' : ", random.choice('Hello World'))

当我们运行上面的程序,它产生的结果类似以下内容:
returns a random number from range(100) :  19
returns random element from list [1, 2, 3, 5, 9]) :  9
returns random character from string 'Hello World' :  r

上一篇: Python3循环 下一篇: Python3数字