|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 戴宇轩 于 2015-3-21 11:32 编辑
random模块有以下常用的函数: ['random', 'uniform', 'randint', 'choice', 'sample', 'randrange', 'shuffle']
#########################
首先你要了解……
x = [1, 10] 代表 1 <= x <= 10
x = [1, 10) 代表 1 <= x < 10
x = (1, 10] 代表 1 < x <= 10
x = (1, 10) 代表 1 < x < 10
1. random()
随机生成一个 [0, 1) 的浮点数- >>> import random
- >>> random.random()
- 0.5081351950612368
复制代码
2.uniform(a, b)
随机生成一个 [a, b] 的浮点数- >>> import random
- >>> random.uniform(10, 20)
- 19.44935373514052
- >>> random.uniform(20, 10)
- 16.220864603020107
复制代码
3. randint(a, b)
随机生成一个 [a, b] 的整数, a必须大于等于b- >>> import random
- >>> random.randint(0, 9)
- 9
- >>> random.randint(0, 9)
- 7
复制代码
4. choice(seq)
seq为可迭代对象, 从中抽取一项- >>> import random
- >>> seq = ['i', 'love', 'fishc']
- >>> random.choice(seq)
- 'i'
- >>> random.choice(seq)
- 'fishc'
复制代码
5. sample(population, k)
population为可迭代对象, 从中抽取k项, 0 <= k <= len(population)- >>> import random
- >>> population = [1, 2, 3, 4, 5]
- >>> random.sample(population, 2)
- [1, 3]
- >>> random.sample(population, 3)
- [1, 2, 5]
复制代码
6. randrange(start[, stop[, step]])
相当于random.choice(range(start[, stop[, step]]))- >>> import random
- >>> random.randrange(0, 100, 25)
- 25
- >>> random.randrange(0, 100, 25)
- 75
复制代码
7. shuffle(x)
在不改变内存中位置的情况下打乱x- >>> import random
- >>> x = [1, 2, 3, 4, 5]
- >>> random.shuffle(x)
- >>> x
- [3, 1, 2, 4, 5]
复制代码 |
|