Python で使うと便利なライブラリ (2016/08/18 更新)
Python で便利だと思って使うようになったライブラリのメモ。
知識増えて使えるようになったら随時更新 (最終更新 2016/08/18)
標準ライブラリ
all, any
- http://docs.python.jp/3.5/library/functions.html#all:Python3.5 all
- 引数の iterable のすべての要素 (or どれか1つの要素) が真なら True を返す処理。
t = [True, True, True] f = [True, True, False] print(all(t)) # True print(all(f)) # False print(any(f)) # False
- 2つのリストのチェックに使ってみた
la = [1, 2, 3] lb = [1, 2, 4] ### All 関数なし flag = False if len(la) == len(lb) : flag = True for a, b in zip(la, lb) : if a != b : flag = False break print(flag) ### All 関数あり。 print(len(la) == len(lb) and all([a == b for a, b in zip(la, lb)]))
collections.defaultdict
- http://docs.python.jp/3.5/library/collections.html#collections.defaultdict:Python3.5 defaultdict
- collectionsは通常のlist, dict等のサブクラス群で、便利な処理が揃っている。
- 引数 default_factory に「対応するkeyが無かったときに生成されるvalueの型」を入れる。
- int を入れると、新規keyのvalueとして0が入って自動生成。
- 引数 default_factory に「対応するkeyが無かったときに生成されるvalueの型」を入れる。
- 例えば数え上げ処理
import random data = [random.randint(0, 10) for i in range(100)] ### defaultdict 無し counter01 = {} for datum in data : if datum not in counter01 : counter01[datum] = 1 else : counter01[datum] += 1 print(counter01) ### defaultdict あり from collections import defaultdict counter02 = defaultdict(int) for datum in data : counter02[datum] += 1 print(counter02)
3rd Party
docopt
- https://github.com/docopt/docopt:git docopt
- Description や Usage を書くのと起動引数パーサ書くのが同時にできて便利!!
- 日本語 Description も OK。
# -*- coding: utf-8 -*- from docopt import docopt __doc__ = """ Description: Docopt test module 日本語説明も大丈夫 Usage: {f} [-h | --help] {f} [-v | --version] {f} [<opt>] --arg0=<arg> Options: -h --help Show this screen. --version Show version. <opt> Option0 --arg0=<arg> Argument0 """.format(f = __file__) if __name__ == '__main__' : args = docopt(__doc__, version = "0.0.1") print("arg0 = {0}".format(args["--arg0"])) print("opt0 = {0}".format(args["<opt>"]))
- 実行結果
$ python test.py yyy --arg0=xxx arg0 = xxx opt0 = yyy $ # 「[]」で囲った <opt> 分は省略可能 $ python test.py --arg0=xxx arg0 = xxx opt0 = None $ # --arg0 は指定必須。フォーマットが違うと Usage 表示 $ python docopt_test.py yyy Usage: docopt_test.py [-h | --help] docopt_test.py [-v | --version] docopt_test.py [<opt>] --arg0=<arg>