赞
踩
只能生成大于 0 且小于 1 之间的小数 (float类型)
import random
print(random.random()) # 0.445551017368668
print(random.random()) # 0.09191193089709782
#由random.random()的扩展因为其不能指定参数。而random.uniform(1, 3)指定了一到三之间的浮点数, (注意: 返回浮点数。不包括一和三)
import random
print(random.uniform(1,3)) # 1.8079224989194222
print(random.uniform(1,3)) # 2.2382904648981112
import random
# 生成大于等于 2 且小于等于 5 之间的整数 (包括2,包括5, 表示的是开区间)
print(random.randint(2,5)) # 3
print(random.randint(2,5)) # 2
print(random.randint(2,5)) # 3
import random
# 生成大于等于 2 且小于 5 之间的整数(顾头不顾尾和range一样取不到5)
print(random.randrange(2,5)) # 4
print(random.randrange(2,5)) # 3
print(random.randrange(2,5)) # 4
import random
res = random.choice([1,'23',[4,5]])
print(res,type(res))
'''多次输出后的结果
23 <class 'str'>
1 <class 'int'>
[4, 5] <class 'list'>
'''
import random
res = random.sample([1,2,3,'23',[4,5]],2) # 从列表里随机取出 2 个元素组合
print(res,type(res)) # [[4, 5], '23'] <class 'list'> (存放在一个列表里)
res = random.sample([1,2,3,'23',[4,5]],3) # # 从列表里随机取出 3 个元素组合
print(res,type(res)) # ['23', 1, 2] <class 'list'>
import random
item = [1,2,3,4,5]
random.shuffle(item) # 随机打乱item这个列表中元素的顺序。
print(item) # [4, 5, 1, 2, 3]
a-z
对应的十进制是 97-122
A-Z
对应的十进制是 65-90
import random def auth_code(count=6): res = '' for i in range(count): lower = chr(random.randint(97,122)) # 随机小写字母 upper = chr(random.randint(65,90)) # 随机大写字母 num = str(random.randint(0,9)) # 随机数字 res2 = random.choice([lower,upper,num]) # 三者之间随机取走一个 res += res2 # 字符拼接 return res print(auth_code(6)) # tmvp60 print(auth_code(6)) # Bl7h51 print(auth_code(6)) # Y9xa33 print(auth_code(6)) # 787zR3
import random def auth_code(count=6): l = [] for i in range(count): lower = chr(random.randint(97, 122)) upper = chr(random.randint(65,90)) num = str(random.randint(0,9)) res2 = random.choice([lower,upper,num]) l.append(res2) return "".join(l) print(auth_code()) # 6O22yl print(auth_code()) # g24X4u print(auth_code()) # 0V220P print(auth_code()) # 9sgnO8
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。