python,random随机数的获取
  随机数⽣成
  ⾸先我们需要在程序中引⼊random》》》import random as r
  r.random()⽤于⽣成⼀个随机的浮点数,
>>> print(r.random())
0.23928059596578843
>>>
  r.uniform(10,20),⽣成⼀个随机的浮点数,如果a>b 则a为上限,b为下限。如果a<b,则b为上限>>> print(r.uniform(10,20))
15.995495884011348
python生成1到100之间随机数>>> print(r.uniform(20,10))
13.179092381602349
>>>
#如果没有给定a,b那么会报错
>>> print(r.uniform())
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
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 "<pyshell#6>", line 1, in <module>
print(r.randint())
TypeError: randint() missing 2 required positional arguments: 'a'and'b'
>>> print(r.randint(1,10))
1
 >>> print(r.randint(10,1))
  Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
  print(r.randint(10,1))
  File "D:\python\lib\random.py", line 222, in randint
  return self.randrange(a, b+1)
  File "D:\python\lib\random.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 "<pyshell#25>", line 1, in <module>
r.sample('qweasd',8)
File "D:\python\lib\random.py", line 319, in sample
raise ValueError("Sample larger than population or is negative") ValueError: Sample larger than population or is negative
# 等于字符长度时
>>> 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]
>>>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。