Python3 choice() 関数
説明
choice()このメソッドは、リスト、タプル、または文字列のランダムな項目を返します。
構文
以下は choice() メソッドの構文です:
import random random.choice( seq )
注意:choice() は直接アクセスできません。random モジュールをインポートし、random 静的オブジェクトを介してこのメソッドを呼び出す必要があります。
パラメータ
- seq -- リスト、タプル、または文字列を指定できます。
戻り値
ランダムな項目を返します。例
以下は choice() メソッドを使用した例です:
例
#!/usr/bin/python3
import random
print ("range(100) からランダムな数値を返します : ",random.choice(range(100)))
print ("リスト [1, 2, 3, 5, 9]) からランダムな要素を返します : ", random.choice([1, 2, 3, 5, 9]))
print ("文字列 'サンプル' からランダムな文字を返します : ", random.choice('サンプル'))
import random
print ("range(100) からランダムな数値を返します : ",random.choice(range(100)))
print ("リスト [1, 2, 3, 5, 9]) からランダムな要素を返します : ", random.choice([1, 2, 3, 5, 9]))
print ("文字列 'サンプル' からランダムな文字を返します : ", random.choice('サンプル'))
上記の例を実行した後の出力結果は次のとおりです:
从 range(100) 返回一个随机数 : 68 从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : 2 从字符串中 'サンプル' 返回一个随机字符 : u
以下はランダムパスワードジェネレータの簡単な実装です:
例
import random
import string
def generate_password(length):
# パスワードに使用可能な文字セットを定義
chars = string.ascii_letters + string.digits + string.punctuation
# ランダムに文字を選択してパスワードを生成
password = ''.join(random.choice(chars) for _ in range(length))
return password
random_pwd = generate_password(6) # 長さ6のパスワードを出力
print(random_pwd)
import string
def generate_password(length):
# パスワードに使用可能な文字セットを定義
chars = string.ascii_letters + string.digits + string.punctuation
# ランダムに文字を選択してパスワードを生成
password = ''.join(random.choice(chars) for _ in range(length))
return password
random_pwd = generate_password(6) # 長さ6のパスワードを出力
print(random_pwd)
上記の例ではgenerate_password()この関数は、生成するパスワードの長さを表す整数パラメータ length を受け取り、Python 標準ライブラリの random モジュールと string モジュールを使用してランダムなパスワードを生成します。string.ascii_lettersすべてのアルファベット(大文字と小文字)を含み、string.digitsすべての数字を含み、string.punctuationすべての句読文字を含みます。
random.choice(chars) は文字セット chars からランダムに1文字を選択し、join() メソッドが生成された文字を連結してパスワードを形成します。
上記の例を実行した後の出力結果は次のとおりです:
R?u|<Kその他の拡張