1
4

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標準ライブラリのお勉強(1)

Last updated at Posted at 2017-01-06

batteries included

最近知ったのだが、Pythonはbatteries included(バッテリー同梱)な言語と言われているらしい。
標準ライブラリだけでも充分戦える、というニュアンスらしい。

データ分析からこの言語を知った身としては、numpyやpandas、scikit-learnなどの外部ライブラリに目が行きがち。
でも、batteries includedな言語であれば、まずは標準ライブラリを知っておいても損ないよね、知っておくべきだよね、ということで、学習の過程で知った標準ライブラリについて、忘れないようにメモ。
こちらも、順次追加予定。

random

文字通り、ランダムデータの生成、操作などに関する機能を持つ。
今回は、「ランダムでシーケンスをシャッフルしたい」と思い、ググった結果引っかかった、以下の2つをメモ。

random.shuffle(list)

文字通り、listをシャッフルする。

import random
list = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(list)
list
Out[5]: 
[6, 8, 4, 9, 1, 7, 3, 0, 5, 2]

シャッフルしたlistを返すのではなく、listそのものをシャッフルするっぽい。
また、シャッフルできるのは数字型だけみたい。
数字型以外でも可能なようです(コメント欄参照)

文字列をシャッフルしたくてたどり着いたのは、以下。

random.sample(list, k)

listから、k回だけランダムに抽出したものを返す。
つまり、文字列の文字数分だけ抽出すれば、文字列自体をシャッフルしたことになる。

list2 = 'abcdef'
''.join(random.sample(list2, len(list2)))
Out[7]: 
'dbeacf'

こちらは、listそのものをいじることはしないっぽい。

list2
Out[8]: 
'abcdef'

ほうほう。

1
4
2

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?