Python3 choice()函數

choice() 方法從列表,元組或字串中返回一個隨機的專案。

語法

以下是 choice() 方法的語法:
choice( seq )

注:此函數無法直接訪問,所以我們需要導入 random 模組,然後用數學靜態對象調用這個函數。 

參數

  • seq -- 這可以是一個列表,元組或字串...

返回值

此方法返回一個隨機的專案。

示例

下麵的例子顯示 choice() 方法的使用。
#!/usr/bin/python3
import random

print ("returns a random number from range(100) : ",random.choice(range(100)))
print ("returns random element from list [1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9]))
print ("returns random character from string 'Hello World' : ", random.choice('Hello World'))

當我們運行上面的程式,它產生的結果類似以下內容:
returns a random number from range(100) :  19
returns random element from list [1, 2, 3, 5, 9]) :  9
returns random character from string 'Hello World' :  r

上一篇: Python3迴圈 下一篇: Python3數字