競プロを戦う上で必須となるPythonの基礎文法を紹介します。
具体的な適用例を省略している場合があるため、その際はリンクをご参照ください。
必要だと感じた文法は随時更新していきます。
#1.基礎文法
[・if – break文][16]
[16]:https://techacademy.jp/magazine/24522
[・タプルの基礎][18]
要素の取り出しはリストと同じ。
[18]:https://www.sejuku.net/blog/23964
[・辞書の基礎][5]
list(辞書.keys())
#list()としないとdict_keys(リスト)で出力される。
[5]:https://www.javadrive.jp/python/dictionary/index8.html
[・文字列のスライス][17]
val = "いろはにほへと散りぬるを"
、val[0] 'い'
、val[3:7] 'にほへと'
[17]:https://techacademy.jp/magazine/23323
[・リストのスライス][15]
リスト[-4:]
# -4番目から末尾までの全要素を取り出す
[15]:https://atmarkit.itmedia.co.jp/ait/articles/2012/08/news013.html
[・リストから要素を削除する方法][24]
1.del リスト[インデックス] / del リスト[開始インデックス:終了インデックス]
2.リスト[開始インデックス:終了インデックス] = []
3.リスト.pop() / リスト.pop(インデックス)
4.リスト.remove(値)
5.リスト.clear()
[24]:https://www.javadrive.jp/python/list/index8.html
[・リストに要素を追加する方法][25]
1.リスト.append([6, 7])
# 要素[6, 7]を末尾に追加
2.リスト.extend([4, 5])
# リストの要素を末尾に追加
3.リスト.extend(6)
# TypeError
4.リスト.extend((3, 4))
# タプルの要素がリスト末尾に追加される
5.リスト.insert(5, [3.25, 3.5])
# 第2引数に指定した値は単一の要素として挿入される。 print(リスト) # [0, 1, 2, 2.5, 3, [3.25, 3.5], 4]
[25]:https://www.atmarkit.co.jp/ait/articles/2012/11/news015.html
[・文字列や数値の連結][20]
','.join(リスト)
#リストの要素をカンマ区切りで出力。数値は文字列に変換
[20]:https://www.sejuku.net/blog/41752
[・区切り出力sep()][6]
print(5, 4, sep=' ')
#5 4
[6]:https://blog.pyq.jp/entry/Python_kaiketsu_200604
[・zip関数と辞書の内包表記][3]
dict = {key:value for key, value in zip(keys, values)}
[3]:https://dot-blog.jp/news/python-dict-comprehensions/
[・特定要素の数][2]
['aa', 'bb', 'cc', 'aa'].count('aa') → 2
from collections import Counter Counter(['aa', 'bb', 'cc', 'aa']) → Counter({'aa': 2, 'bb': 1, 'cc': 1})
[2]:https://hibiki-press.tech/python/count/103#toc5
[・リストの要素を昇順または降順に並び替える][4]
sorted(リスト)
は元のリストの順番は変わらない。
リスト.sort()
は元のリストは参照できなくなる。
[4]:https://techacademy.jp/magazine/28106
[・組み合わせ][8] [順列]
lis = [1,2,3,4] a = [pair for pair in itertools.combinations(lis, 2)] [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[順列]:https://qiita.com/BlueSilverCat/items/77f4e11d3930d7b8959b
[8]:https://qiita.com/Mohrey/items/b0afc8edc5fed742b68a
[・逆順ループ][9]
for x in reversed(range(0, 5)):
[9]:https://www.python.ambitious-engineer.com/archives/1757
[・無名関数 lambda][26]
関数の引数に関数を渡したい時に有用
リスト = [0, -1, 2, -3, 4, -5] list(map(lambda n : n**2 if n>0 else n**2*-1, リスト))
#[0, -1, 4, -9, 16, -25]
[もう一つのリンク][27]
[26]:https://www.headboost.jp/python-lambda/
[27]:https://note.nkmk.me/python-lambda-usage/
[・filter関数 - 配列から関数の条件にあう要素を抽出][28]
words = ['Python', 'CSS', 'HTML', 'JavaScript'] x = filter(lambda word:True if len(word) > 5 else False, words) print(list(x))
#['Python', 'JavaScript']
[28]:https://dot-blog.jp/news/python-filter-function/
・プログラム実行時間計測
[timeモジュール
][22] [timeitモジュール
][23]、[jupyterなら%%timeit
][23]
[22]:https://www.sejuku.net/blog/23955
[23]:https://note.nkmk.me/python-timeit-measure/
・numpy行列
[1.行列作成][12]:np.array(リスト/タプル)
[2.列の取り出し][19]:行列[:, 0]
#1列目の取り出し
[3.対角要素][10]:np.diag(行列)
[4.転置][11]:行列.T
numpy.transpose(行列)
[5.配列の1次元化][13]:行列.flatten()
[6.二次元配列のかっこをはずして出力][14]:for i in 二次元配列: print(*i)
[7.条件を満たす要素数をカウント][29] : np.count_nonzero(条件式)
[10]:https://www.headboost.jp/numpy-diagonal/
[11]:https://note.nkmk.me/python-numpy-transpose/
[12]:https://www.headboost.jp/python-numpy-array/
[13]:https://deepage.net/features/numpy-flatten.html#2%E6%AC%A1%E5%85%83%E9%85%8D%E5%88%97%E3%82%921%E6%AC%A1%E5%85%83%E9%85%8D%E5%88%97%E3%81%AB%E5%A4%89%E6%8F%9B
[14]:https://pillow545.com/programming/way_to_output#5flatten
[19]:https://www.mathpython.com/ja/numpy-matrix-column/
[29]:https://note.nkmk.me/python-numpy-count/
・テクニック
[if~else → リスト.append(max())][21]:実行時間はif~elseのほうが短いことに注意。
[21]:https://qiita.com/radiol/items/6b4a312d20da8ade811b
#2.ご意見・ご感想をお待ちしております
当方、未熟なプログラマーのため、よりよいコード等ありましたら教えていただけると幸いです。
皆様のメッセージをお待ちしております。