0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python tips

0
Last updated at Posted at 2019-11-07

python tips まとめ

備忘録として残しておきます。

文字→ascii。ascii→文字への変換

ordでアスキーコード取得

>>> ord('a')
97

chr で文字取得

>>> chr(97)
a

リストの生成

リスト包括で書くと、メモリ保存しないから実行速度が速い。

.py
num = 1000000000

# 通常の書き方
list_1 = []
for i in range(num):
   list_1.append(i)

# リスト内包表記
list_2  = [i for i in range(num)]

また、@konandoiruasaさんから以下のものが内包表記によるものとトントンか若干早いとアドバイスいただきました。

.py
import numpy as np
a = list(np.arange(num, dtype=int))

さなざまなものを連結させる "join"

join では文字列、数値、パスを連結させることができます。
" ".joinで使います。

.py
list = ['a', 'b', 'c']
result = ''.join(list)
print(result)

## abc

listに文字と数値がある場合、map関数でstrに全て変換

.py
list = ['a', 'b', 1 ]
result = map(str, list)
result1 = ''.join(result)
print(result1)

## ab1

split で分割

.py
str1 = "a,b,c"
sep = str1.split(",")
print(sep)
## ['a', 'b', 'c’]

np.arrayとlistの変換

.py

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に書き出す方法

.py

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) 

終わりに

随時、追加していきたいと思います。
ご指摘があれば、ビシバシお願いします。

0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?