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
>>> 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]
>>> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM