LoginSignup
2
6

More than 1 year has passed since last update.

Python チートシート

Last updated at Posted at 2021-12-28

チートシート

自分用のメモです。

基本はドキュメント見るべし。

Python 言語リファレンス — Python 3.10.0b2 ドキュメント

文法

if

if_stmt ::=  "if" assignment_expression ":" suite
             ("elif" assignment_expression ":" suite)*
             ["else" ":" suite]
# 基本
if (tmp.text != '6:00 - 6:45\nAvailable'):
    result = tmp.find_element(By.CLASS_NAME, 'fc-time')
    print("yes")

# 要素のあるなし
if tmp:
    print("ある")
else:
    print("ない")

while

while_stmt ::=  "while" assignment_expression ":" suite
                ["else" ":" suite]
# 無限ループ
while True:
    os.system('afplay /System/Library/Sounds/Hero.aiff')

for

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]
for i in myDict:
    print(i)

# dictで使いやすいforの回し方
for i in myDict.keys():
    print(i)

try except

try_stmt  ::=  try1_stmt | try2_stmt
try1_stmt ::=  "try" ":" suite
               ("except" [expression ["as" identifier]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]
try2_stmt ::=  "try" ":" suite
               "finally" ":" suite
try:
    print("ok")
except:
    print("error")

演算子

比較演算子

演算子 内容
a == b a が b と等しい
a != b a が b と異なる
a < b a が b よりも小さい
a > b a が b よりも大きい
a <= b a が b 以下である
a >= b a が b 以上である
a is b a が b と等しい
a is not b a が b と異なる
a in b a が b に含まれる (a, b は共に文字列、または、b はリストやタプル)
a not in b a が b に含まれない (a, b は共に文字列、または、b はリストやタプル)

関数

def 関数名
  処理
# 絶対値
def abs(x):
    if x >= 0:
        return x
    return -x

# べき乗
def power(x, y):
    return x ** y

## 位置引数
power(2, 3)

## キーワード引数
power(x=2, y=3)

## 引数のデフォルト値
def power2(x=1, y=1):
    return x ** y

# 引数のデフォルト値を設定した場合、キーワード引数を省略できる
power(x = 3)

データ構造

辞書型

辞書の複製

新しい辞書 = コピー元の辞書.copy()

dictからランダムにひとつ取得

import random

d = {(0, 4): 0, (0, 5): 0, (1, 1): 0, (1, 2): 0, (1, 3): 0, (2, 6): 0}
tmp = random.choice(list(d.items()))
print(type(tmp))
print(tmp)
# キーを取得
print(f"{tmp[0]}")

リスト

listからランダムに取得

index = random.randrange(0, len(ansList))

条件付きリスト作成

要素が数字の場合は無視して、リストを作成する

def removeDigit(tl):
    new = [i for i in tl if not i.isdigit()]
    return new

タプル

tupleの取り出し方

# インデックスを指定して取り出す。
print(myTuple[0])

文字列関係

re.sub()でマッチした文字列を置換先の文字列内で使用する方法

raw記法を使うことできれいに書けます。

tmp = re.sub('(a|b)', r'\1\n', 'aiueobcd')
print(tmp)

ランダム関係

Python ランダムな数列を作成する方法。重複有無、全列挙 - Qiita

print関係

Python printについてメモ - Qiita

ソート関係

Python JSONデータをソートする - Qiita

パッケージ公開

Python poetryを使用したPyPIパッケージ公開 - Qiita

環境

# 仮想環境を作成
python3 -m venv .venv && source .venv/bin/activate

# インストールされているパッケージの確認
pip freeze

# requirements.txtの作成
pip freeze > requirements.txt

# requirements.txtからインストール
pip install -r requirements.txt

# 仮想環境を修了
deactivate

# インストール
pip3 install Jupyter

# 忘れがちなjupyterの拡張子 
code test.ipynb

# pyenv
pyenv install --list
pyenv install 3.9.16
pyenv global 3.9.16 

その他

# 指定したディレクトリ直下のファイル名の一覧をリストとして取ってくる関数
def fileLst(dirpath):
    return glob.glob(dirpath + '/*')

参考

【Python入門】if文で条件分岐する書き方をサンプルコードとあわせて解説

2
6
0

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
2
6