LoginSignup
1
3

More than 5 years have passed since last update.

setを使って乱数作ってみた

Last updated at Posted at 2017-11-03

set型とは…

set型とは、集合を扱うための型で、listと同じように複数の値を入れれる型です。
listとの違いは

・要素が1個ずつしか入れられない(重複しない)
・要素に順番がつかない

などがある。

早速本題へ

まず、0~9のリストを作る。

>>>l=[str(x) for x in range(0,10)]
#l=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

次にsetにする。

>>>set(l)
{'7', '8', '5', '0', '4', '1', '6', '9', '2', '3'}

これで0~9がぐちゃぐちゃになったヤツができた。

が、しかし

>>> set(l)
{'7', '8', '5', '0', '4', '1', '6', '9', '2', '3'}
>>> set(l)
{'7', '8', '5', '0', '4', '1', '6', '9', '2', '3'}
>>> set(l)
{'7', '8', '5', '0', '4', '1', '6', '9', '2', '3'}
>>> set(l)
{'7', '8', '5', '0', '4', '1', '6', '9', '2', '3'}

あれ?これ、まさか…何度やっても一緒になるのか…???

シェル上では何回やっても変わらないようなので、テキストファイルを作って読み取ってみることにした。

>>> l_text="\n".join(l)
>>> with open("a.txt","w") as w:
...     w.writelines(l_text)

これでa.txtを作って、

list2set.py
with open("a.txt") as f:
    lines=f.readlines()
lines=[str(i).replace("\n","") for i in lines]
X=set(lines)
print(X)

結果は

$ python list2set.py
{'5', '7', '3', '6', '1', '8', '4', '0', '9', '2'}
$ python list2set.py
{'9', '0', '3', '4', '7', '6', '8', '2', '1', '5'}
$ python list2set.py
{'2', '6', '0', '5', '4', '9', '8', '7', '3', '1'}

おっ、なんかそれっぽいやん!
でも確認のためforで回すと

list2set.py
for i in range(0,20):
    with open("a.txt") as f:
        lines=f.readlines()
    lines=[str(i).replace("\n","") for i in lines]
    X=set(lines)
    print(X)
$ python list2set.py
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}
{'3', '2', '6', '5', '1', '8', '9', '0', '7', '4'}

と、同じになった。(左端顔みたい)
時間とかメモリの状態とかが関係してんのかなー、知らんけど

結果

乱数ジェネレーターっぽいものができた。
疑問はいくつか残るけど眠いのでまた今度調べます(( _ _ ))..zzzZZ

1
3
1

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
3