Python中choice用法与三元操作

来源:互联网 发布:今天eia数据公布 编辑:程序博客网 时间:2024/05/16 09:21

今天随手写了一个随机答案生成器,用到了random模块的choice和三元运算符。以下是代码部分:

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

0 0