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

WBOY
Release: 2016-06-10 15:12:31
Original
3383 people have browsed it

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

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

choice( seq )

Copy after login

注意:此函数是无法直接访问的,所以我们需要导入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')

Copy after login

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

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

Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!