LoginSignup
1
0

More than 5 years have passed since last update.

python3のメモ

Last updated at Posted at 2017-09-26

パッケージマネジャー

sudo python3 -m pip install -U pip

文法

配列

一番後ろを指定

array[-1]

後ろから二番目を指定

array[-2]

便利な関数

標準ライブラリ

組み込み型

組み込み関数

https://docs.python.jp/3/library/functions.html
インタプリタに組み込まれている関数

zip

https://docs.python.jp/3/library/functions.html?highlight=zip#zip
それぞれのイテラブルから要素を集めたイテレータを作成する。

x = [1, 2, 3]
y = [4, 5, 6]
zipped = [[x, y] for x, y in zip(x, y)]
zipped #[[1, 4], [2, 5], [3, 6]]

zipped = {y:x for x, y in zip(x, y)}
zipped #{4: 1, 5: 2, 6: 3}
enumerate

https://docs.python.jp/3/library/functions.html?highlight=enumerate#enumerate
インデックスと値を返す。

x = [1, 2, 3]
y = [(v, idx) for (idx, v) in enumerate(x)]
y #[(1, 0), (2, 1), (3, 2)]
map

https://docs.python.org/ja/3.6/library/functions.html#map
第一引数で指定した関数で第二引数で渡したiterableオブジェクトを処理します。

def main():
    lst = [-1, 3, -5, 7, -9] 

    # 関数 
    print(list(map(abs, lst))) 

    # ラムダ式 
    print(list(map(lambda x: x * 2, lst))) 

    # 関数形式の標準演算子 
    # operator.negは引数を負にした数値を返す
    import operator 
    print(list(map(operator.neg, lst)))

if __name__ == '__main__':
    main()
filter

https://docs.python.jp/3/library/functions.html?highlight=filter#filter
第一引数で指定した関数が返したブーリアンがTrueとなるような第二引数の要素を返す。

def main():
    lst = [-1, 3, -5, 7, -9] 

    # 関数 

    # ラムダ式 
    print( list( filter(lambda x: x >= 0, lst) ))

    # 関数形式の標準演算子 

if __name__ == '__main__':
    main()

関数型プログラミング用モジュール

itertoolsモジュール

itertools.accumulate

https://docs.python.jp/3/library/itertools.html?highlight=product#itertools.accumulate
第一引数の要素を一つにまとめた値を第二引数で与えた関数で計算する。第二引数を省略した場合は和を計算。

import itertools
for item in itertools.accumulate([1,2,3,4]):
    print(item)

def multiply(a,b):
    return a*b

for item in itertools.accumulate([1,2,3,4], mutiply):
    print(item)
itertools.chain

https://docs.python.jp/3/library/itertools.html?highlight=product#itertools.chain
引数全体が一つのイテラブルであるかのように振る舞う。

import itertools
for item in itertools.chain([1,2], [3,4]):
    print(item)

functoolsモジュール

モジュールは高階関数、つまり関数に影響を及ぼしたり他の関数を返したりする関数のためのものです。一般に、どんな呼び出し可能オブジェクトでもこのモジュールの目的には関数として扱えます。

functools.reduce

https://docs.python.jp/3/library/functools.html?highlight=reduce#functools.reduce
第一引数の関数をイテラブルの要素に対してに累積的に適用し、単一の値に縮約。畳み込み関数とか呼ばれる。

from functools import reduce

# 関数
print(reduce(add, [-1, 3, -5, 7, -9]))

# ラムダ
print(reduce(lambda x, y: x+y, [-1, 3, -5, 7, -9]))

operatorモジュール

https://docs.python.jp/3/library/operator.html
簡単なラムダ式を書くくらいならこっちを使おう。

仮想環境

仮想環境の作成

mkdir tmpdir
python3 -m venv tmpdir

仮想環境に入る

. tmpdir/bin/activate

仮想環境から出る

deactivate
sudo dnf install mecab mecab-devel mecab-ipadic
# Fedora25
sudo dnf install redhat-rpm-config
pip3 install mecab-python3

進捗を視覚化する

from tqdm import tqdm
for i in tqdm(range(10000)):
    ...

データ分析・機会学習・ディープラーニング

いろいろダウンロード

sudo pip3 install pystan numpy scipy matplotlib ipython jupyter scikit-learn pandas pillow beautiful-soup html5lib seaborn

jupyter

拡張機能の追加

pip3 install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
mkdir -p $(jupyter --data-dir)/nbextensions

vimバインディング

cd $(jupyter --data-dir)/nbextensions
git clone https://github.com/lambdalisue/jupyter-vim-binding vim_binding
jupyter nbextension enable vim_binding/vim_binding

vimバインディングにしたときにJupyterモードに入るときのショートカットキーがShift + Escに設定されています。私のPCだとこのShift + Escが入力できなかった(Caps LockをEscにしているが、どうしてもShift + Caps Lockがデフォルトの挙動になってしまう)ので、バインディングをCtrl + Escに変更した。

vim ~/.local/share/jupyter/nbextensions/vim_binding/vim_binding.js

で72行目を変更

...
//'Shift-Esc': CodeMirror.prototype.leaveNormalMode,
'Ctrl-Esc': CodeMirror.prototype.leaveNormalMode,
...

デバッグ

import pdb; pdb.set_trace()

デバッガコマンドについては以下参照
https://docs.python.jp/3/library/pdb.html

1
0
0

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
0