Home  >  Article  >  Backend Development  >  Python中的choice()方法使用详解

Python中的choice()方法使用详解

WBOY
WBOYOriginal
2016-06-10 15:12:313341browse

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

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

choice( seq )

注意:此函数是无法直接访问的,所以我们需要导入random模块,然后我们需要使用random对象来调用这个函数。
参数

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

返回值

该方法返回一个随机项。
例子

下面的例子显示了choice()方法的使用。

#!/usr/bin/python
import random

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

当我们运行上面的程序,它会产生以下结果:

choice([1, 2, 3, 5, 9]) : 2
choice('A String') : n


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn