random.random() / random.randint() / random.choice()
| 対応: | Python 2(2000) |
|---|
『random』モジュールが提供する乱数生成・ランダム選択・シャッフルの関数です。ゲーム・テストデータ生成・サンプリングなどに使用します。
構文
import random # 0.0以上1.0未満の浮動小数点数を返す random.random() # 指定した範囲のランダムな整数を返す random.randint(a, b) # 指定した範囲のランダムな浮動小数点数を返す random.uniform(a, b) # シーケンスからランダムに1つ選んで返す random.choice(シーケンス) # シーケンスからk個の要素を重複なしで選んでリストを返す random.sample(シーケンス, k) # シーケンスをランダムに並び替える(インプレース) random.shuffle(リスト)
関数一覧
| 関数 | 概要 |
|---|---|
| random.random() | 0.0以上1.0未満の浮動小数点数をランダムに返します。 |
| random.randint(a, b) | a以上b以下のランダムな整数を返します(両端を含みます)。 |
| random.uniform(a, b) | a以上b以下のランダムな浮動小数点数を返します。 |
| random.choice(シーケンス) | 空でないシーケンス(リスト・タプル・文字列など)からランダムに1要素を選んで返します。 |
| random.sample(シーケンス, k) | シーケンスからk個の要素を重複なしでランダムに選び、新しいリストで返します。元のシーケンスは変更されません。 |
| random.shuffle(リスト) | リストの要素をランダムに並び替えます(インプレース)。戻り値は『None』です。 |
| random.seed(値) | 乱数生成のシードを設定します。同じシードを指定すると同じ乱数列が再現できます。 |
サンプルコード
random_basic.py
import random
print(random.random())
dice = random.randint(1, 6)
print(f"サイコロ: {dice}")
temp = random.uniform(20.0, 30.0)
print(f"気温: {temp:.1f}℃")
実行すると次のように出力されます。
python3 random_basic.py 0.8444218515250481 サイコロ: 1 気温: 27.0℃
random_choice_sample.py
import random
colors = ["red", "blue", "green", "yellow", "purple"]
picked = random.choice(colors)
print(f"選ばれた色: {picked}")
winners = random.sample(colors, k=3)
print(f"TOP3: {winners}")
cities = ["Tokyo", "Osaka", "Nagoya", "Sapporo", "Fukuoka"]
print(f"行き先: {random.choice(cities)}")
実行すると次のように出力されます。
python3 random_choice_sample.py 選ばれた色: blue TOP3: ['red', 'green', 'yellow'] 行き先: Tokyo
random_shuffle_seed.py
import random cards = list(range(1, 14)) random.shuffle(cards) print(cards) random.seed(42) print(random.randint(1, 100))
実行すると次のように出力されます。
python3 random_shuffle_seed.py [10, 4, 5, 7, 3, 9, 6, 8, 2, 11, 1, 12, 13] 82
よくあるミス
よくあるミス1: shuffle() の戻り値を使おうとする
『random.shuffle()』はリストをインプレースで並び替えるため戻り値は『None』です。戻り値を変数に代入しても意味がありません。
import random colors = ["red", "blue", "green"] shuffled = random.shuffle(colors) print(shuffled)
次のように記述します。
import random colors = ["red", "blue", "green"] random.shuffle(colors) print(colors)
よくあるミス2: セキュリティ用途に random を使う
パスワードやトークンの生成など、暗号的に安全な乱数が必要な場面では『random』モジュールは適していません。そのような用途には『secrets』モジュールを使うと安全です。
import random import string chars = string.ascii_letters + string.digits password = "".join(random.choice(chars) for _ in range(16)) print(password)
次のように記述します。
import secrets import string chars = string.ascii_letters + string.digits password = "".join(secrets.choice(chars) for _ in range(16)) print(password)
概要
Pythonの『random』モジュールはメルセンヌ・ツイスタアルゴリズムを使用しており、高品質な擬似乱数を生成します。ゲーム・シミュレーション・テストデータ生成など多くの用途に使えます。
『random.shuffle()』はリストをインプレース(元のリスト自体を変更)で並び替えるため戻り値は『None』です。元のリストを変更したくない場合は事前にコピーしてからシャッフルできます。
『random』モジュールはセキュリティ用途には使用しない方がよい場面があります。パスワードやトークンの生成など、暗号的に安全な乱数が必要な場合は『secrets』モジュールの『secrets.token_hex()』や『secrets.choice()』を使うと安全です。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。