Python中choice用法与三元操作
2015-07-21 21:11
746 查看
今天随手写了一个随机答案生成器,用到了random模块的choice和三元运算符。以下是代码部分:
运行效果如下:
关于choice函数:
random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。下面是使用choice的一些例子:
print random.choice(“学习Python”)
print random.choice([“JGood”, “is”, “a”, “handsome”, “boy”])
print random.choice((“Tuple”, “List”, “Dict”))
关于三元运算符:
(1) variable = a if exper else b
(2) variable = exper and a or b
相当于C语言中的:
import sys; import random; num = 3; if len(sys.argv) == 2: num = int(sys.argv[1]) for i in range(num): for j in range(5): print(random.choice("ABCD"), end='') print(' ', end='\n' if (i + 1) % 4 == 0 or i == num - 1 else '')
运行效果如下:
关于choice函数:
random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。下面是使用choice的一些例子:
print random.choice(“学习Python”)
print random.choice([“JGood”, “is”, “a”, “handsome”, “boy”])
print random.choice((“Tuple”, “List”, “Dict”))
关于三元运算符:
(1) variable = a if exper else b
(2) variable = exper and a or b
相当于C语言中的:
exper ? a : b
相关文章推荐
- 50个强大的Python模块
- Python 学习笔记一之模块探究学习
- [2015-07-19] python005
- python 2.4 与 python 3.0 的比较
- Python日志之Python函数
- Python学习日志之Python函数
- python 匹配中文和英文
- python杂记
- Python学习笔记
- Python CGi URL 中文以及特殊转义字符的处理
- python Sys module
- Python自学笔记之函数式编程5——返回函数
- python time module
- python os module
- python list方法
- python API开发
- wxpython
- Python的文件
- [Python学习] 简单爬取CSDN下载资源信息
- Python package和folder