random模塊

1、 random

    全部關於隨機相關的內容都在random模塊中dom

2、相關功能

1. random()

  • 產生(0, 1)之間的小數
import random

print(random.random())  # 0.2622839912972649

2. uniform(a, b)

  • 產生(a, b)之間的小數
import random

print(random.uniform(3, 10))  # 3.1025846246337134

3. randint(a, b)

  • 產生[a, b]之間的整數
import random

print(random.randint(1, 10)) # 7

4. randrange(a, b, step)

  • 產生[a:b:step]裏的一個數
  • step默認等於1
import random

print(random.randrange(1, 10, 2)) # 3

5. choice(string/tuple/list)

  • 產生對象裏的其中一個元素
import random

print(random.choice([11, 22, 33, 44, [55, 66, 77]]))  # 44

6. sample(string/tuple/list/set)

  • 從對象中任選兩個元素,以列表形式返回
import random

print(random.sample([11, 22, 33, 44], 2))  # [44, 22]

 7. shuffle(list)

  • 隨機打亂順序
  • 返回None
import random

lst = [11, 22, 33, 44, 55]
random.shuffle(lst)
print(lst)  # [11, 55, 44, 33, 22]
相關文章
相關標籤/搜索