概述
随机数生成
首先我们需要在程序中引入random》》》import random as r
r.random()用于生成一个随机的浮点数,
>>> print(r.random())0.23928059596578843
>>>
r.uniform(10,20),生成一个随机的浮点数,如果a>b 则a为上限,b为下限。如果a
>>> print(r.uniform(10,20))15.995495884011348
>>> print(r.uniform(20,10))13.179092381602349
>>>
#如果没有给定a,b那么会报错
>>> print(r.uniform())
Traceback (most recent call last):
File "", line 1, in
print(r.uniform())
TypeError: uniform() missing 2 required positional arguments: 'a' and 'b'
>>> print(r.randint())
r.randint(a,b),生成一个随机的整数,a 是下限,b是上限。下限必须小于上限
>>> print(r.randint())
Traceback (most recent call last):
File"", line 1, in
print(r.randint())
TypeError: randint() missing2 required positional arguments: 'a' and 'b'
>>> print(r.randint(1,10))1
>>> print(r.randint(10,1))
Traceback (most recent call last):
File "", line 1, in
print(r.randint(10,1))
File "D:pythonlibrandom.py", line 222, in randint
return self.randrange(a, b+1)
File "D:pythonlibrandom.py", line 200, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (10,2, -8)
>>>
r.randrange(a,b,1or2),随机取出指定范围内的奇偶数,1奇数 2偶数
>>> r.randrange(0,10,2)6
>>> r.randrange(0,10,1)1
>>> r.randrange(0,10,1)7
>>>
r.choice('qwertuiopolkjhgffdsa')所及取出某一个字符
>>> print(r.choice('qwertyuiop[]lkjhgfdsazxcvbnm'))
k>>> print(r.choice('qwertyuiop[]lkjhgfdsazxcvbnm'))
n>>> print(r.choice('qwertyuiop[]lkjhgfdsazxcvbnm'))
t>>>
r.sample(str,num),会随机输出num个字符,且num一定小于等于len(str)
#小于字符长度时
>>> r.sample('qweasd',2)
['d', 'q']#大于字符长度时
>>> r.sample('qweasd',8)
Traceback (most recent call last):
File"", line 1, in r.sample('qweasd',8)
File"D:pythonlibrandom.py", line 319, insampleraise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than populationor isnegative#等于字符长度时
>>> r.sample('qweasd',6)
['s', 'd', 'a', 'e', 'w', 'q']>>>
洗牌,也就是随机排序
>>> items = [1,2,3,4,5,6]>>>r.shuffle(items)>>>items
[3, 6, 1, 5, 2, 4]>>>
最后
以上就是知性水壶为你收集整理的python取随机小数_python,random随机数的获取的全部内容,希望文章能够帮你解决python取随机小数_python,random随机数的获取所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复