Python
https://scrapbox.io/files/6703ec90a453de001c59d0ca.png
Iterable
ソート
sort()
返り値: None
sorted()
返り値: Iterable
逆転(反転)
reversed()
[::-1]
スライス
めちゃ苦手で毎回 ChatGPT に聞いている
最後尾を除くには、hoge[:-1]
先頭を除くには、hoge[1:]
冪乗
a の b 乗
a**b
pow(a, b)
#再帰関数
dict
in dict の扱い
x in dict とした場合にはキーに含まれるかどうかを判定するみたい
ファイルの読み込み
Pythonでファイルの読み込み、書き込み(作成・追記) | note.nkmk.me
open()
第一引数で指定したパスのファイルについてファイルオブジェクトが作成される
code:python
with open(path) as f:
print(type(f))
# <class '_io.TextIOWrapper'>
with ブロックが便利
ブロックの終了時に自動的にクローズしてくれる
f.read()
ファイル全体を文字列として取得
code:python
with open(path) as f:
s = f.read()
print(type(s))
print(s)
# <class 'str'>
# line 1
# line 2
# line 3
ファイルオブジェクトは with ブロックが終了するとクローズされるが、代入した変数は with ブロック外でももちろん使用できる
f.readlines()
ファイル全体をリストとして取得
code:python
with open(path) as f:
l = f.readlines()
print(type(l))
print(l)
# <class 'list'>
# 'line 1\n', 'line 2\n', 'line 3'
最終行意外は改行コード \n を含む