Python3 choice()函式

2019-10-16 23:12:06
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