第四章 4 random模块

random获取随机数


>>> import random
>>> random.randint(0,100)
61
>>> random.randint(0,100)
39
>>> random.randint(0,100)
50
>>> random.randint(0,100)
>>> random.randrange(1,4)
1
>>> random.randrange(1,100)
4
>>> random.randrange(1,200)
4
>>>

随机浮点数

>>> random.random()
0.3616696459433273
>>> random.random()
0.10851486484033135
>>> random.choice('adj32@45!#2')
'3'
>>> random.choice('adj32@45!#2')
'3'
>>> random.choice('adj32@45!#2')
'3'
>>> random.sample('adj32@45!#2',3)
['4', 'a', '2']
>>> random.sample('adj32@45!#2',3)
['a', '@', '2']
>>> import string
>>> string.digits
'0123456789'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_lowercase+string.digits
'abcdefghijklmnopqrstuvwxyz0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> s=string.ascii_lowercase+string.digits+string.punctuation
>>> s
'abcdefghijklmnopqrstuvwxyz0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> a=string.ascii_lowercase+string.digits
>>> a
'abcdefghijklmnopqrstuvwxyz0123456789'
>>> random.sample(a,5)
['m', '5', 'n', 't', 'j']
>>> ''.join(random.sample(a,5))
'mx0ib'
>>> ''.join(random.sample(a,5))
'tvz2s'
>>>

洗牌

>>> d=list(range(0,100))
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> random.shuffle(d)
>>> d
[70, 87, 9, 62, 29, 17, 82, 65, 69, 55, 88, 95, 18, 6, 54, 12, 8, 7, 2, 30, 20, 91, 39, 51, 14, 93, 0, 68, 19, 49, 98, 97, 76, 25, 22, 67, 94, 78, 1, 86, 42, 28, 71, 10, 79, 46, 74, 73, 43, 90, 40, 32, 99, 96, 75, 64, 37, 13, 77, 27, 31, 63, 23, 84, 92, 38, 26, 52, 3, 4, 15, 36, 45, 58, 21, 16, 53, 34, 57, 41, 60, 56, 85, 5, 66, 59, 83, 11, 72, 44, 33, 81, 50, 35, 61, 48, 80, 47, 89, 24]
>>>

猜你喜欢

转载自blog.csdn.net/qq_42936973/article/details/82177150