2
3

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.

pythonでrandomを使ってみる。

Last updated at Posted at 2017-12-21

なにぶん、初心者なもので。
randomの使い方もわからんかったのです。

shiracamus様よりご指摘頂いた点を修正致します

python3でコンソール立ち上げて…

まずはモジュールを使えるようにする。
import random

単純な乱数取得

>>> print(random.random())
0.7053217152160873
>>> print(random.random())
0.8461746389717953
>>> print(random.random())
0.12047153256715915
>>> print(random.random())
0.31427179976283537

リストのシャッフル

>>> data = ["A", "B", "C"]

>>> data
['A', 'B', 'C']

>>> random.shuffle(data)
>>> data
['A', 'C', 'B']
>>> random.shuffle(data)
>>> data
['B', 'C', 'A']
>>> random.shuffle(data)
>>> data
['A', 'C', 'B']
>>> random.shuffle(data)
>>> data[1]
'A'
>>> random.shuffle(data)
>>> data[1]
'C'
>>> random.shuffle(data)
>>> data[1]
'A'
>>> random.shuffle(data)
>>> data[1]
'A'
>>> random.shuffle(data)
>>> data[1]
'A'
>>> random.shuffle(data)
>>> data[1]
'A'
>>> random.shuffle(data)
>>> data[1]
'A'
>>> random.shuffle(data)
>>> data[1]
'C'
>>>

リストの数が少ないからあまり変化してるようには見えませんね…。

チョイス(追記しました)

>>> data =  ["A", "B", "C", "D", "E"]
>>>
>>>
>>> import random
>>> random.choice(data)
'B'
>>> random.choice(data)
'E'
>>> random.choice(data)
'B'
>>> random.choice(data)
'D'
>>> random.choice(data)
'D'
>>> random.choice(data)
'B'
>>>

シャッフルはリストを破壊的にまぜまぜするんすね。
1個だけとるならチョイスのほうが楽ですね…。

slackbotでランダムな回答をしようと思って使ってみました。
randomはもっと色々使えそう。

2
3
3

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?