random.choice() 是 Python random 模組常用的函數,能從列表、元組或字串等序列中隨機回傳一個元素。本文介紹其語法、參數、回傳值與實際範例。
import random
random.choice(seq)
從序列中隨機挑選的一個元素。
#!/usr/bin/python
import random
print "choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9])
print "choice('A String') : ", random.choice('A String')
choice([1, 2, 3, 5, 9]) : 2
choice('A String') : n
注意: 執行結果每次不同,因為是隨機選取。