Python标准库 random模块
Python标准库-random模块
random 模块包含许多随机数生成器. 基本随机数生成器(基于 Wichmann 和 Hill , 1982 的数学运算理论) 可以通过很多方法访问, 如 Example 2-29 所示. 2.17.0.1. Example 2-29. 使用 random 模块获得随机数字 File: random-example-1.py import random for i i
random 模块包含许多随机数生成器.
基本随机数生成器(基于 Wichmann 和 Hill , 1982 的数学运算理论) 可以通过很多方法访问, 如 Example 2-29 所示.
2.17.0.1. Example 2-29. 使用 random 模块获得随机数字
File: random-example-1.py
import random
for i in range(5):
# random float: 0.0 <= number < 1.0
print random.random(),
# random float: 10 <= number < 20
print random.uniform(10, 20),
# random integer: 100 <= number <= 1000
print random.randint(100, 1000),
# random integer: even numbers in 100 <= number < 1000
print random.randrange(100, 1000, 2)
0.946842713956 19.5910069381 709 172
0.573613195398 16.2758417025 407 120
0.363241598013 16.8079747714 916 580
0.602115173978 18.386796935 531 774
0.526767588533 18.0783794596 223 344
注意这里的 randint 函数可以返回上界, 而其他函数总是返回小于上界的值. 所有函数都有可能返回下界值.
Example 2-30 展示了 choice 函数, 它用来从一个序列里分拣出一个随机项目. 它可以用于列表, 元组, 以及其他序列(当然, 非空的).
2.17.0.2. Example 2-30. 使用 random 模块从序列取出随机项
File: random-example-2.py
import random
# random choice from a list
for i in range(5):
print random.choice([1, 2, 3, 5, 9])
2
3
1
9
1
在 2.0 及以后版本, shuffle 函数可以用于打乱一个列表的内容 (也就是生成一个该列表的随机全排列). Example 2-31 展示了如何在旧版本中实现该函数.
2.17.0.3. Example 2-31. 使用 random 模块打乱一副牌
File: random-example-4.py
import random
try:
# available in 2.0 and later
shuffle = random.shuffle
except AttributeError:
def shuffle(x):
for i in xrange(len(x)-1, 0, -1):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random.random() * (i
相关文档:
这两个基本上都是在循环的时候用。
Python
代码 < type="application/x-shockwave-flash" width="14" height="15" src="http://cloudhe.javaeye.com/javascripts/syntaxhighlighter/clipboard_new.swf" src="http://cloudhe.javaeye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=for%20i% ......
对 Python 函数的"调制",是指对其做出合乎需求的设置。具体的调制方法,是将其参数设为固定值(常数)。
设定单一的参数值
原先的函数是这样的:
>>> def foo(cooked, standard):
... print "foo called with cooked: %s, standard: %s" % \
... (cooked, standard)
调用它:
>>> foo('a', ......
先给出一个四人团对
Decorator mode
的定义:
动态地
给一个
对象
添加一些
额外的职责
。
再来说说这个模式的好处:认证,权限检查,记日志,检查参数,加锁,等等等等,这些功能和系统业务无关,但又是系统所必须的,说的更明白一点,就是面向方面的编程(
AOP
)。
AOP
把与业务无关的代码十分干净 ......
zz from: http://blog.sina.com.cn/s/blog_4b5039210100f1tu.html
原文有点小错误,改了一点点。
我们知道python只定义了6种数据类型,字符串,整数,浮点数,列表,元组,字典。但是C语言中有些字节型的变量,在python中该如何实现呢?这点颇为重要,特别是要在网络上进行数据传输的话。
python提供了一个struc ......