random函数
1. random.random :取浮点数,在0到1直接随机取值
>>> import random >>> random.random() 0.6171837421239116 >>> random.random() 0.8984304298471243 >>> help(random.random) Help on built-in function random: random(...) method of random.Random instance random() -> x in the interval [0, 1).
2. random.uniform:取浮点数,可自定义取值范围
>>> random.uniform(1,3) 1.315795759972287 >>> random.uniform(1,3) 1.4898884772992593 >>> random.uniform(1,3) 2.6892324719347864
3. random.randint:设置取值范围,包括最后面一位
>>> random.randint(1,4) 4 >>> random.randint(1,4) 1 >>> random.randint(1,4) 2 >>> random.randint(1,4) 3
4. random.randrange:设置取值范围,不包括最后一位
>>> random.randrange(1,4) 1 >>> random.randrange(1,4) 2 >>> random.randrange(1,4) 3 >>> random.randrange(1,4) 1
5. random.choice:从序列中取值,如字符串、元组、列表等
>>> random.choice('hello world') 'l' >>> random.choice('hello world') 'w' >>> random.choice([3,4,6,7,23]) 23 >>> random.choice([3,4,6,7,23]) 6
6. random.sample:也是从序列中取值,可以设置取值长度
>>> random.sample("hello world",2) ['o', 'w'] >>> random.sample("hello world",2) ['l', 'w'] >>> random.sample([5,34,6,43,54,7],2) [34, 54] >>> random.sample([5,34,6,43,54,7],2) [34, 5] >>> random.sample([5,34,6,43,54,7],3) [34, 54, 7] >>>
7. random.shuffle:洗牌,将原有的顺序打乱
>>> pai = [1,2,3,4,5,6,7,8] >>> pai [1, 2, 3, 4, 5, 6, 7, 8] >>> random.shuffle(pai) >>> pai [4, 8, 1, 5, 2, 6, 7, 3] >>> random.shuffle(pai) >>> pai [1, 2, 4, 6, 8, 5, 7, 3]
博主小学未毕业,请勿口喷!