python函数random研读

摘自python数据收集一书的一段文字:大多数随机数算法都努力创造一种呈均匀分布且难以预测的数据序列,但是在算法初始化阶段都需要提供随机数"种子"(random seed)。而完全相同的种子每次会产生同样的"随机"数序列,因此我用系统时间作为随机数序列生成的起点。
random.seed(a=None, version=2)

    Initialize the random number generator.

    If a is omitted or None, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).

    If a is an int, it is used directly.

    With version 2 (the default), a str, bytes, or bytearray object gets converted to an int and all of its bits are used. With version 1, the hash() of a is used instead.

    Changed in version 3.2: Moved to the version 2 scheme which uses all of the bits in a string seed.


Functions for integers:
random.randint(a, b)

    Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).


Functions for sequences:
random.choice(seq)

    Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.


random.random()

    Return the next random floating point number in the range [0.0, 1.0).


>>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
>>> population = [val for val, cnt in weighted_choices for i in range(cnt)]
>>> random.choice(population)
'Green'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值