5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

randomモジュールについてまとめる

Last updated at Posted at 2019-05-01

はじめに

標準ライブラリであるrandomモジュールを使うことが多いのですが, 生成する乱数が整数や小数の場合で使い分けする必要があるのでまとめてみることにしました.

乱数生成

関数 使い方
random() 0.0以上1.0未満の浮動小数点数を生成
uniform() 任意の範囲の浮動小数点数を生成
randrange() 任意の範囲, ステップの整数を生成
randint() 任意の範囲の整数を生成

random()

0.0以上1.0未満の浮動小数点数が生成されます.

print([random.random() for i in range(5)])
# [0.4771975525622725, 0.6876604312377167, 0.6221870340760471, 0.18161004411536352, 0.27937966825312976]

uniform()

引数をa以上b以下に設定すると, その間の浮動小数点数が生成されます.

print([random.uniform(10,50) for i in range(5)])
# [30.755611303844862, 15.487989783227757, 13.013386711111226, 31.356856664548157, 26.50324863369832]

引数を同じ値に設定すると, その値が生成されます.

print([random.uniform(50,50) for i in range(5)])
# [50.0, 50.0, 50.0, 50.0, 50.0]

randrange()

randrange(start, stop, step)は, range(start, stop, step)の要素からランダムな値(整数)を返します.

print([random.randrange(100,1000,50) for i in range(5)])
# [750, 250, 450, 700, 950]

引数のstart, stepを省略するとstart=0, step=1となります.

print([random.randrange(50) for i in range(5)])
# [45, 22, 6, 37, 19]

randint()

引数をa以上b以下に設定すると, その間の整数が生成されます.

print([random.randint(10,50) for i in range(5)])
# [23, 50, 41, 31, 26]

要素をランダムに選択

choice()

choice()は, 引数のシーケンスオブジェクトからランダムに一つの要素を選択します. リストやタプル, 文字列で使用できます.

test = ['a', 'b', 'c', 'd', 'e']
print(random.choice(test))
# d

sample()

sample()は, 引数のシーケンスオブジェクトからランダムに複数の要素を重複なしで選択します.

test = ['a', 'b', 'c', 'd', 'e']
print(random.sample(test,3))
# ['e', 'c', 'b']

choices()

choices()は, 引数のシーケンスオブジェクトからランダムに複数の要素を重複ありで選択します.
引数kで取り出す要素数を指定する. デフォルトでは1になっています.

test = ['a', 'b', 'c', 'd', 'e']
print(random.choices(test,k=3))
# ['a', 'e', 'e']

ランダムにシャッフル

rand.shuffle()は引数のシーケンス型オブジェクトの要素をランダムにシャッフルします.
戻り値はなく, オブジェクト自体をシャッフルします.

test = ['a', 'b', 'c', 'd', 'e']
random.shuffle(test)
print(test)
# ['a', 'e', 'b', 'd', 'c']

参考サイト

【Python入門】randomモジュールの使い方まとめ
Pythonでランダムな小数・整数を生成するrandom, randrange, randintなど

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?