はじめに
Pythonはほとんど覚えていない!
しかし、度々使用する必要があり、同じ事を何度も調べている気がするので、今後は備忘録を残そうと思います。
調べるごとに追加していこうと思います。
個人メモなため役に立たないかもしれませんが、よかったら使ってみてください。
型変換
test_str = '100'
int(test_str)
print()で改行なし
print('text', end='')
PATHの生成
# add path
path = './'
path = os.path.join(path, 'dir')
# generate path
path = ['./', 'dir']
path = os.path.join(*path_list)
インデックス番号と共にループ
enumerate()
を使うと、カウンタの加算を書かなくてもループ時に取得できる。
test_list = ['test1', 'test2', 'test3']
for idx, test in enumerate(test_list):
print('{} : {}'.format(idx, test))
文字列操作
文字列の分割
test_str = 'Hello World'
test_str.split() #スペースなどで区切る → ['Hello', 'World']
test_str.split('o') #'o'で区切る → ['Hell', ' W', 'rld']
文字列の結合
test_str = 'Hello World'
test_list = test_str.split()
test_join = ''
test_join = test_join.join(test_list) #間に`test`を入れて結合 → 'HelloWorld'
test_join = ' '
test_join = test_join.join(test_list) #間に`test`を入れて結合 → 'Hello World'
文字列の置換
test_str = 'Hello World'
test_str.replace('o', 'p') #'o'を'p'に変換 → 'Hellp Wprld'
test_str.replace('o', 'p', 1) #1回だけ'o'を'p'に変換 → 'Hellp World'
辞書
キーの削除
削除するだけなら2行目のみで良いが、キーが存在しない場合も考えると、2行にしておいた方が安全そう。
if 'key' in dic:
del dic['key']
ループ内でキーを削除しようとするとエラーが発生するので、以下のようにする
for key in list(dic):
if ...: # 好みの条件
del dic[key]
math
インポート
import math
from math import * ## math.をつける必要がなくなる
数式
math.sin(radian)
math.cos(radian)
math.tan(radian)
math.exp(x)
math.log(x)
math.pow(x, y)
math.sqrt(x)
定数
math.pi
math.e
numpy
インポート
import numpy as np
行列生成
# ゼロ行列生成
zeros_array = np.zeros((row, column))
# イチ行列生成
ones_array = np.ones((row, column))
# 数値行列生成
value_array = np.full((row, column), value)
内積
np.dot(A, B)
OpenCV
インポート
import cv2
画像を読み込み
img = cv2.imread(path)
画像を描画
cv2.imshow('img', img)
cv2.waitKey(0) # 引数は描画時間
cv2.destroyAllWindows()
画像を書き込み
cv2.imread(path, img)