python的 random模块

random模块用于生成随机数。

random.randint(a, b):

 生成随机整数n (a <= n <= b)

>>> random.randint(1,10)
10

random.random():

生成随机浮点数n (0 <= n < 1.0)

>>> print random.random()
0.5240641875
>>> print random.random()
0.234854238114

random.uniform(a, b):

生成随机浮点数n (如果a>b,则b <= n <= a。如果b>a,则a <= n <= b)

>>> print random.uniform(1, 10)
3.35351445677
>>> print random.uniform(1, 10)
2.46947884885
>>> print random.uniform(100, 10)
45.9025693327

random.randrange([start], stop[, step]):

在start到stop的范围内,根据由step指定步长形成的集合里随机获取一个元素。

换而言之,它是从range(start, stop, step)里随机获取一个元素,等价于random.choice(range(start, stop, step))。

(官方文档说:This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.)

>>> random.randrange(1, 10, 2)
9
>>> random.randrange(1, 10)
8
>>> random.randrange(10)
7
注意:按语法说明写“random.randrange(, 10, 2)”或者“random.randrange(, 10)”会提示语法错误。

random.choice(seq):

从序列seq中随机获取一个元素。

seq范指list, tuple, 字符串等等。seq为空时返回一个IndexError错误。

>>> print random.choice("Python")
t
>>> print random.choice(["a", "ab", "abc"])
ab
>>> print random.choice(("a", "ab", "abc"))
ab

random.shuffle(x[, random])

打乱列表x里元素的顺序(不适用于元组和字符串)

>>> p = (["a", "ab", "abc"])
>>> random.shuffle(p)
>>> p

>>> p = (("a", "ab", "abc"))
>>> random.shuffle(p)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/random.py", line 275, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item assignment

>>> p = ("Python")
>>> random.shuffle(p)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/random.py", line 275, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

random.seed([x])

初始化随机数生成器,如果不提供x或者为None,就以系统时间做为种子。

这篇文档的代码在没有使用seed()时总是生成相同的数字,没有任何随机。http://blog.csdn.net/huithe/article/details/5254137,代码如下:

import os,random,sys,time

while True:

    father = os.fork()

    if father:
        time.sleep(2)
        rd = 7
    else:
        # random.seed()
        rd = random.choice([2,3,4,5])
        print rd
        time.sleep(2)
        sys.exit(0)

的确没有生成随机数,但是程序在cygwin下运行会出错:

$ python test7.py
5
5
5
      1 [main] python 10704 D:\cygwin\bin\python.exe: *** fatal error - unable to remap \\?\D:\cygwin\lib\python2.6\lib-dynload\_codecs_cn.dll to same address as parent: 0x360000 != 0x3D0000
Stack trace:
Frame     Function  Args
0028B3C8  6102796B  (0028B3C8, 00000000, 00000000, 00000000)
0028B6B8  6102796B  (6117EC60, 00008000, 00000000, 61180977)
0028C6E8  61004F1B  (611A7FAC, 61243684, 00360000, 003D0000)
End of stack trace
      0 [main] python 14488 fork: child 10704 - died waiting for dll loading, errno 11
Traceback (most recent call last):
  File "test7.py", line 5, in <module>
    father = os.fork()
OSError: [Errno 11] Resource temporarily unavailable

把random.seed()前面的#去掉,生成的数字是随机的。

{

据唐唐说cygwin的fork()有问题,这篇文档也证实了这个说法:http://www.lc365.net/blog/b/8585/ 

cygwin官方文档(http://cygwin.com/cygwin-ug-net/highlights.html)里看到这一句:

The fork call in Cygwin is particularly interesting because it does not map well on top of the Win32 API. This makes it very difficult to implement correctly. Currently, the Cygwin fork is a non-copy-on-write implementation similar to what was present in early flavors of UNIX.

}

random.sample(population, k)

在population序列(字符串、列表、元组都可以)中随机获取由k指定数量的元素。

>>> random.sample((["a", "ab", "abc", "abcd", "abcde", "abcdef"]), 3)
['a', 'ab', 'abcde']
>>> random.sample((("a", "ab", "abc", "abcd", "abcde", "abcdef")), 3)
['abc', 'abcdef', 'ab']
>>> random.sample(("python"), 3)
['o', 'h', 'p']
如果要从一个范围的数字里随机获取指定数量的数,最快最节省内存的方法:

>>> random.sample(xrange(1, 1000000 ,2), 3)
[717481, 410151, 700227]

random模块还有其他一些方法就不一一列举了。








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值