描述
這個choice()方法從列表、元組或字符串中返回一個隨機項。
用法
以下是語法choice()方法 -
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
相關用法
- Python 3 Number ceil()用法及代碼示例
- Python 3 Number cos()用法及代碼示例
- Python 3 Number tan()用法及代碼示例
- Python 3 Number atan()用法及代碼示例
- Python 3 Number max()用法及代碼示例
- Python 3 Number sin()用法及代碼示例
- Python 3 Number round()用法及代碼示例
- Python 3 Number acos()用法及代碼示例
- Python 3 Number shuffle()用法及代碼示例
- Python 3 Number fabs()用法及代碼示例
- Python 3 Number log()用法及代碼示例
- Python 3 Number randrange()用法及代碼示例
- Python 3 Number hypot()用法及代碼示例
- Python 3 Number exp()用法及代碼示例
- Python 3 Number degrees()用法及代碼示例
- Python 3 Number sqrt()用法及代碼示例
- Python 3 Number seed()用法及代碼示例
- Python 3 Number log10()用法及代碼示例
- Python 3 Number radians()用法及代碼示例
注:本文由純淨天空篩選整理自 Python 3 - Number choice() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。