Python choice() 関数

Python 数字Python 数値


説明

choice()メソッドはリスト、タプル、または文字列のランダムな項目を返します。


構文

以下は choice() メソッドの構文です:

import random

random.choice( seq  )

注意:choice() は直接アクセスできません。random モジュールをインポートし、random 静的オブジェクトを介してこのメソッドを呼び出す必要があります。


パラメータ

  • seq -- リスト、タプル、または文字列を指定できます。

戻り値

ランダムな項目を返します。

例

以下は choice() メソッドを使用した例です:

#!/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

Python 数字Python 数値

その他の拡張機能