易截截图软件、单文件、免安装、纯绿色、仅160KB

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 字符串


Python 字符串
字符串是 字符的序列 。字符串基本上就是一组单词。
我几乎可以保证你在每个Python程序中都要用到字符串,所以请特别留心下面这部分的内容。下面告诉你如何在Python中使用字符串。
使用单引号(')
你可以用单引号指示字符串,就如同'Quote me on this'这样。所有的空白,即空格和制表符都照原样保留。 ......

Python 序列


Python 序列
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
使用序列
例9.5 使用序列
#!/usr/bin/python
# Filename: seq.py
shoplist ......

Python实现“各类型文件统计”功能

不多说了,直接看代码吧!
import os
path = 'e:/Download/'
kzm = []
kzmTemp = set()
kzmTemp2 = []
dict = {}
for root,dirs,files in os.walk(path):
    for file in files:
        ext = os.path.splitext(file)[1][1:]
      ......

Python之感

从去年还没毕业就接触Python,上周有些无聊重新再看一遍,发现其确实不错。语法简单,一个下午基本了解,使用Pydev插件在Eclipse中进行开发基本上没有任何障碍。重点是其效率很高,不需编译直接运行。比较适合进行数据的预处理。不错,以后有机会好好用用。 ......

Python的lambda函数与排序

前几天看到了一行求1000的阶乘的Python代码:
print
  
reduce
(
lambda
  
x
,
y
:
x
*
y
,
  
range
(
1
,
  
1001
))

一下子被python代码的精简
与紧凑所折服,故对代码进行了简单的分析。
reduce与range都是Python的内置函数。
range(1,10 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号