Maison  >  Article  >  développement back-end  >  Python中的choice()方法使用详解

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

WBOY
WBOYoriginal
2016-06-10 15:12:313341parcourir

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


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn