python tips まとめ
備忘録として残しておきます。
文字→ascii。ascii→文字への変換
ord
でアスキーコード取得
>>> ord('a')
97
chr
で文字取得
>>> chr(97)
a
リストの生成
リスト包括で書くと、メモリ保存しないから実行速度が速い。
num = 1000000000
# 通常の書き方
list_1 = []
for i in range(num):
list_1.append(i)
# リスト内包表記
list_2 = [i for i in range(num)]
また、@konandoiruasaさんから以下のものが内包表記によるものとトントンか若干早いとアドバイスいただきました。
import numpy as np
a = list(np.arange(num, dtype=int))
さなざまなものを連結させる "join"
join では文字列、数値、パスを連結させることができます。
" ".join
で使います。
list = ['a', 'b', 'c']
result = ''.join(list)
print(result)
## abc
listに文字と数値がある場合、map関数でstrに全て変換
list = ['a', 'b', 1 ]
result = map(str, list)
result1 = ''.join(result)
print(result1)
## ab1
split で分割
str1 = "a,b,c"
sep = str1.split(",")
print(sep)
## ['a', 'b', 'c’]
np.arrayとlistの変換
import numpy as np
list = [1,2,3]
a = np.array(list)
print(a)
## array([1, 2, 3])
b = a.tolist()
print(b)
##[1, 2, 3]
csvに書き出す方法
import pandas as pd
log = pd.DataFrame(
columns=['epoch', 'lr', 'train_loss', 'val_loss']
)
tmp = pd.Series([ epoch, lr, train_loss, val_loss ], index=log.columns)
log = log.append(tmp, ignore_index=True)
log.to_csv('log.csv'), index=False)
終わりに
随時、追加していきたいと思います。
ご指摘があれば、ビシバシお願いします。