雑食性雑感雑記

知識の整理場。ため込んだ知識をブログ記事として再構築します。

Python で使うと便利なライブラリ (2016/08/18 更新)

Python で便利だと思って使うようになったライブラリのメモ。
知識増えて使えるようになったら随時更新 (最終更新 2016/08/18)

標準ライブラリ

all, any

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

  • 例えば数え上げ処理
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

# -*- 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>

PythonのConfigParserでカッチリとしたコンフィグ設定をする

概要

  • Pythonのモジュール「ConfigParser」を使うと、設定ファイルをパースして使えて便利!!
  • …なのだが、値は全て文字列なので、そこから適切な形に変換しないと――。
  • 別途設定ファイルのための設定を作り、制御できるようにしてみた。
続きを読む

Python のクラスメンバ設定には setattr が便利 (かも)

概要

  • Python のクラスメンバ設定の方法について調べてみた。
  • 引数が増えたときは、dictionary 使った方が良さそう。
  • 引数チェックするのにコード増える⇒効率良く書くには――
    • setattr うまく使うと楽に書ける!!
続きを読む

Chrome の画面を chrome extension で操作してみる。

概要

  • Chrome extension を使って、Popup 部から HTML の DOM を操作してみる。
    • とりあえず背景色を変化させてみる。
    • ( 将来的には、コレをベースに色々操作できるように―― )
続きを読む