【AtCorderメモ・Python】チートシート
AtCoderに挑戦しているとき、毎回調べていることをメモする。
※本記事は、必要に応じて定期的に追記していく。
入力
よく使うもの
type of var | example | Python |
---|---|---|
str | "ab" | a = input() |
str | "ab cd" | a, b = input().split() |
list(str) | "ab cd ef" | a = list(input().split()) |
int | 10 | i = int(input()) |
int | 10 20 | i, j = map(int, input().split()) |
list(int) | 10 20 30 | i = list(map(int, input().split())) |
参考
出力
Yes
or No
を1行で切り替え(内包表記)
flag = True #True:'Yes', False:'No' ans = 'Yes' if flag else 'No' print(ans)
参考
リストを単一文字列に変換(join)
#type: list(str) str_list = ['d','o','g'] ans = ''.join(str_list) print(ans) #'dog' #type: list(int) *文字列への変換が必要 int_list = [1,2,3] ans = ' '.join(map(str, int_list)) print(ans) #'1 2 3'
参考
その他
リスト内包表記
リスト内包表記でfor
,if
,else
を活用。
#for (map関数のようなイメージ) a_list = [1,2,3] x_list = [a_i*2 for a_i in a_list ] print(x_list) #[2,4,6] #for / if (map関数+filter関数のようなイメージ) a_list = [1,2,3] x_list = [a_i*2 for a_i in a_list if a_i%2==1] print(x_list) #[2,6] #for / if /else a_list = [1,2,3] x_list = [a_i*2 if a_i%2==1 else a_i*10 for a_i in a_list] print(x_list) #[2,20,6]
参考
多次元リストの初期化
多次元リストの初期化時に*
を利用すると、想定外の動きをするので、アンチパターンとして記載。
# OK a_list = [[0] for _ in range(3)] print(a_list) #[[0],[0],[0]] a_list[0].append(1) print(a_list) #[[0,1],[0],[0]] # NG b_list = [[0]]*3 print(b_list) #[[0],[0],[0]] b_list[0].append(1) print(b_list) #[[0,1],[0,1],[0,1]]
参考
多次元リストを複合キーでソート
多次元リストを複合キーでソートする方法を記載。
from operator import itemgetter # (名前, 数学, 英語)の組み合わせ data = [['A', 40, 100], ['B', 70, 100], ['C', 80, 40]] # キー①:英語、キー②:数学で降順にソート data = sorted(data, key=itemgetter(2, 1), reverse=True) # [['B', 70, 100], ['A', 40, 100], ['C', 80, 40]]