LoginSignup
1
1

More than 5 years have passed since last update.

pythonでlist(配列)からランダムに要素を選択する

Posted at

randomモジュールのchoice関数を使うことで、配列からランダムに1つの要素を取得することができます。

ただし、要素数が0の場合Exceptionをraiseするので注意が必要。

>>> import random
>>> random.choice(["hoge","fuga","piyo"])
'piyo'
>>> random.choice(["hoge","fuga","piyo"])
'fuga'
>>> random.choice([])
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib64/python2.7/random.py", line 275, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range
1
1
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
1
1