Python數位choice()
方法從列表,元組或字串返回一個隨機項。
語法
以下是choice()
方法的語法 -
import random
choice( seq )
注意 - 此函式不可直接存取,需要匯入random
模組,然後需要使用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