python之随机模块
python之随机模块
random模块——随机数模块
import random print(random.random()) #(0,1),大于0小于1之间小数 print(random.randint(1,3)) #[1,3],大于等于1且小于等于3之间的整数 print(random.randrange(1,3)) #[1,3),d大于等于1且小于3之间的整数 print(random.choice([1,'23',[4,5]])) #1或23或[4,5] print(random.sample([1,'23',[4,5]],2)) #列表元素任意2个组合 print (random.uniform(1,3)) #大于1小于3的小数,如1.99 random.shuffle(item) #打乱item的顺序 >>> import random >>> print(random.random()) 0.6351521979178012 >>> print(random.randint(1,3)) 3 >>> print(random.choice([1,'23',[4,5]])) 23 >>> print(random.sample([1,'23',[4,5]],2)) [[4, 5], '23'] >>> print (random.uniform(1,3)) 2.9326720236539474
打乱顺序(洗牌功能)
item=[1,3,5,7,9] random.shuffle(item) print(item) >>> item=[1,3,5,7,9] >>> random.shuffle(item) >>> print(item) [1, 5, 9, 3, 7]
随机验证码功能
>>> import random >>> res='' >>> for i in range(6): ... s1=chr(random.randint(65,90)) ... s2=str(random.randint(0,9)) ... res+=random.choice([s1,s2]) ... >>> print(res) U6JRFU ----------------再次优化 >>> import random >>> def make_code(size=4): ... res='' ... for i in range(size): ... s1=chr(random.randint(65,90)) ... s2=str(random.randint(0,9)) ... res+=random.choice([s1,s2]) ... return res ... >>> print(make_code()) 9869 >>> print(make_code(6)) EW1N78