生成几个随机数
import random
print('1', random.random())
print('2', random.random())
print('3', random.random())
1 0.9413002981807297
2 0.24844802601455696
3 0.5170120485722177
- 返回随机生成的一个实数,范围是[0, 1)
实例一:
从1至10中随机取一个整数
print(random.randint(1, 10))
"""
Return random integer in range [a, b], including both end points.
"""
实例二:
类似range()函数 前包后不包,可以设置步长;
可以随机取一个范围内的偶数等…
print(random.randrange(0, 10, 2))
"""
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
"""
实例三:
随机取一个元素或多个元素
l = list(range(1, 10))
print(l)
print(random.choice(l)) # 从列表中随机取一个数
"""
Choose a random element from a non-empty sequence.
"""
print(random.choices(l, k=2)) # 从列表中随机取多个数,可重复
[1, 2, 3, 4, 5, 6, 7, 8, 9]
6
[7, 7]
实例四:
随机取样,不重复
l = list(range(1, 10))
print(l)
print(random.sample(l, 3))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[4, 7, 1]
实例五:
随机多个字母组成字符串
import random
import string
letters = string.ascii_lowercase
print(letters)
print(''.join(random.sample(letters, 3)))
abcdefghijklmnopqrstuvwxyz
uwr
'''
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace
'''