Private Chamber - Python
ノーコメント.
基礎
比較演算子
a == 1
b != 1
c not 1
d < 1
e > 1
f <= 1
g >= 1
論理演算
三つ以上でもカッコは要らない
a == 1 and b == 1
c == 1 or d == 1
以下のどれでもない
a not in (1, 2, 3, 4, 5)
ブーリアン
リテラル
大文字であることに注意
a = True
b = False
文字列
リテラル
シングルクォーテーションが好ましい
a = 'Hello world'
連結
a = 'Hello ' + 'world' # 'Hello world'
b = 'Hello ' 'world' # 'Hello world' (これでも可)
間に挟んで連結
li = [ 'a', 'b', 'c' ]
print(','.join(li)) # 'a,b,c'
改行を含む文章
改行を含む文章
a = '''
シングルまたはダブルクォートを
三つ連ねたもので挟むことで
改行を含む文章でもエスケープなしで
変数に格納できる
'''
フォーマット済み文字列
name = 'Masec'
print(f'Hello, {name}!') # 'Hello, Masec!'
値の埋め込み
tpl = 'a', 'b'
print('%s %% %s' % tpl) # 'a % b'
dict = {'c': 1, 'd': 2}
print('c is %(c)s. d is %(d)s, not %(c)s.' % dict) # 'c is 1. d is 2, not 1.'
一部を取得
a = 'Hello world'
print(a[3:]) # 'lo world'
print(a[:3]) # 'Hel'
print(a[2:5]) # 'llo '
n文字目
s = 'abc'
n = 1
print(s[n-1]) # 'a'
print(s[-1]) # 'c' (最後の文字)
置換
s = 'abcde, abcde'
print(s.replace('bcd', 'XXX')) # 'aXXXe, aXXXe'
print(s.replace('e', 'X', 1)) # 'abcdX, abcde'
検索
s = 'abcabcabc'
print('初めて現れるbは' + str(s.find('b')+1) + '文字目') # '初めて現れるbは2文字目'
print('3文字目以降に初めて現れるbは' + str(s.find('b', 2)+1) + '文字目') # '3文字目以降に初めて現れるbは4文字目'
登場回数
s = 'aaabbc'
print(s.count('b')) # 2
含まれるかどうか
s='abc'
print('b' in s) # True
スペースごとに分割
a = 'Nice to meet you'
print(a.split()) # ['Nice', 'to', 'meet', 'you']
繰り返し
s = 'abc'
print(s*2) # 'abcabc'
数値
リテラル
「0o~」で8進数、「0x~」で16進数、「0b~」で2進数。
小数
「e」または「E」で指数表現ができる。
3.1415926
-0.123456789
-3.1E12
0.1e-23
float型とdouble型があり、float型には誤差が生じるため注意が必要。
print(0.1 + 0.1 + 0.1 == 0.3) # False
from decimal import *
print(Decimal('0.1') + Decimal('0.1') + Decimal('0.1') == Decimal('0.3')) # True
リスト
リテラル
a = [ 'apple', 'banana', 'lemmon' ]
print(a[0]) # 'apple'
要素取得
li = ['a', 'b', 'c']
print(li[1]) # 'b'
print(li[-1]) # 'c'
要素追加
li = [1, 2, 3, 4]
li.append(5)
print(li) # [1, 2, 3, 4, 5]
要素削除
li = [1, 2, 3, 4]
del li[2]
print(li) # [1, 2, 4]
末尾の要素を削除
li = [1, 2, 3, 2]
li.remove(2)
print(li) # [1, 3, 2]
拡張
li = [1, 2, 3]
li.extend([4, 5])
print(li) # [1, 2, 3, 4, 5]
指定した場所に挿入
li = [1, 3]
li.insert(1, 2)
print(li) # [1, 2, 3]
存在確認
li = [1, 2, 3]
print(3 in li) # True
含まれている個数
li = [1, 2, 3, 2, 2]
print(li.count(2)) # 3
検索
li = [1, 2, 3]
print('初めて現れる2は' + str(li.index(2)+1) + '文字目')
最大・最小
li = [1, 2, 3]
print(max(li)) # 3
print(min(li)) # 1
forを内包
print([i for i in range(0, 10, 2)]) # [0, 2, 4, 6, 8]
print([i for i in range(10) if i % 2 == 1]) # [1, 3, 5, 7, 9]
print([c.upper() if c.islower() else c.lower() for c in 'AbCdE']) # ['a', 'B', 'c', 'D', 'e']
print([[x * y for x in range(1, 4)] for y in range(1, 5)]) # [[1, 2, 3], [2, 4, 6], [3, 6, 9], [4, 8, 12]]
タプルから変換
tpl = 1,2,3
li = list(tpl)
並び替える
li = [2, 1, 3]
print(li.sort()) # [1, 2, 3]
タプル
リテラル
要素の変更はできない。
tpl = 'x', 'y'
print(tpl) # ('x', 'y')
print(tpl[0]) # 'x'
要素数
tpl = 1,2,3
len(tpl) # 3
最大・最小
tpl = 1,2,3
print(max(tpl)) # 3
print(min(tpl)) # 1
結合
tpl = 1,2,3
tpl2 = 4,5,6
print(tpl + tpl2) # (1,2,3,4,5,6)
繰り返し
tpl = 1,2,3
print(tpl*2) # (1,2,3,1,2,3)
存在確認
tpl = 1,2,3
print(1 in tpl) # True
何番目か
tpl = 1,2,3
print(tpl.index(1)) # 0
存在する個数
tpl = 1,2,3
print(tpl.count(3)) # 1
並べ替える
tpl = 2,1,3
print(surted(tpl)) # (1,2,3)
反転する
tpl = 1,2,3
print(reversed(tpl)) # (3,2,1)
辞書
リテラル
food = {'type': 'fruits', 'color': 'red', 'taste': 'sweet'}
print(food['type']) # fruits
存在確認
dict = {'a': 1, 'b': 'Hi', 'c': True}
# キーから検索
print('a' in dict.keys()) # True
# 値から検索
print('Hi' in dict.values()) # True
要素取得
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(dict['b']) # 'Hi'
要素追加
dict = {'a': 1, 'b': 'Hi', 'c': True}
dict['d'] = 123
dict.setdefault('e', 'default')
要素の削除
dict = {'a': 1, 'b': 2, 'c': 3}
dict.pop('b')
print(dict) # {'a': 1, 'c': 3}
拡張
拡張
dict = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'c': 4, 'd': 5, 'e': 6}
print(dict.update(dict2)) # {'a': 1, 'b': 2, 'c': 4, 'd': 5, 'e': 6}
長さを取得
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(len(dict)) # 3
キーのみをリスト化
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(list(dict.keys())) # ['a', 'b', 'c']
値のみをリスト化
dict = {'a': 1, 'b': 'Hi', 'c': True}
print(list(dict.values())) # [1, 'Hi', True]
無の型
a = None
具体的な構文
コメントアウト
#とコメント内容の間には半角スペースひとつ入れるのが好ましい
# コメント
"""
複数行コメント(シングルまたはダブルクォート)
"""
変数定義
a = 1
関数
def f(x, y):
print(x+y)
f(1, 2) # 3
条件分岐
if a == b:
# 処理
elif c == d:
# 処理
else:
# 処理
繰り返し処理
range(a)は0~aの整数値を順に出力する
a = ''
for i in range(3):
a += str(i)
print(a) # '012'
li = ['a', 'b', 'c']
b = ''
for i in list_:
b += i
print(b) # 'abc'
例外処理
IndexErrorでリストの存在しない個数目を指定した場合のエラー
cf:例外一覧
try:
print(int('Hi'))
except ValueError:
print('Error') # 'Error'
try: # あらゆるエラー
print(int('Hi'))
except Exception as e:
print(e) # invalid literal for int() with base 10: 'Hi'
クラス定義
class Rectangle:
def __init__(self): # コンストラクタ
self.height = 0
self.width = 0
def set(self, a, b):
self.height = a
self.width = b
使い方
rect = Rectangle()
rect.set(1,2)
print(rect.height) # 1
ユーティリティ
コードの折り込み
あらゆるカッコの中ではjsonのように自由に改行できる
a = 1 + 2 + 3 + 4\
+ 5 + 6 + 7 + 8
型を取得
この際の「str」は特殊な型でありストリング型ではない
type('10') == str # true
型の変更
a = int('100') # ストリングの入力を演算に使う際など
b = str(a) # 数とストリングを連結する際など
c = list('Hello') # [ 'H', 'e', 'l', 'l', 'o' ]
ファイル生成
f = open('○○.txt', 'w')
f.write('Hi')
f.close()
要import
数学関数、定数
抜粋一覧
- math.ceil(x)
- math.comb(n, r) # nCr
- math.fabs(x) # Abs
- math.factrial(int)
- math.floor(x)
- math.gcd(int, int, ...)
- math.isfinite(x)
- math.isinf(x)
- math.isnan(x)
- math.lcm(int, int, ...)
- math.perm(n, r) # nPr
- math.exp(x)
- math.log(x, [base])
- x**y # x^y
- math.pow(x, y)
- math.sqrt(x)
- math.asin(x)
- math.acos(x)
- math.atan(x)
- math.sin(x)
- math.cos(x)
- math.tan(x)
- math.radians(x)
- math.degrees(x)
- math.asinh(x)
- math.acosh(x)
- math.atanh(x)
- math.sinh(x)
- math.cosh(x)
- math.tanh(x)
- math.gamma(x)
- math.pi
- math.e
- math.inf
- math.nan
import math
pi = math.pi # 3.141592653589793
現在時刻を取得
import datetime
now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
print(now.hour) # (現在の時間)
ランダム
import random
rand = random.random() # [0.0, 1.0) からランダムな実数
rand_int = random.randint(a, b) # [a, b] からランダムな整数
li = [ 'a', 'b', 'c', 'd' ]
rand_choice = random.choice(li) # リストからランダムに1つ選択
重複なしでランダムに取り出す
import random
print(random.sample(list_, 10)
ディレクトリのファイル一覧を取得
import os
path = "./○○"
files = os.listdir(path)
files_file = [i for i in files if os.path.isfile(os.path.join(path, i))]
JSONを開く
import json
a = json.load(open('○○.json'), encoding="utf-8")
JSONを書き換える
import json
dict = {'a': 'Hi'}
with open('○○.json', 'w') as changed_file:
json.dump(dict, changed_file, indent=2)
ウィンドウを作成
import tkinter
import tkinter.font as font
frm = tkinter.Tk()
geo = '600x400' # ウィンドウのサイズ
frm.geometry(geo)
frm.title(config.window.name)
fontC = font.Font(family='Helvetica', size=20, weight='bold')
tkinter.Label(
frm,
text='Text', # テキスト
fg='#64ec86', # 文字色
bg='#ffff00', # 文字の背景色
font=fontC
).pack(side='top')
button = tkinter.Button(frm) # ボタン作成
button["text"] = 'Click here!' # ボタンのテキスト設定
button.pack(side='top') # ボタンの設置位置変更
frm.mainloop()
メッセージボックス
from tkinter import messagebox
messagebox.showinfo('タイトル', '内容')
messagebox.showerror('タイトル', '内容')