Python tools
Jupyter Notebook
コマンドラインから起動
jupyter notebook
ショートカット
- セル内のプログラムを実行: Ctrl + Enter
- 下にセルを追加: Shift + Enter
- セルを再度編集可能にする: セルをダブルクリック
- セルの削除: セルを選択、escキー、キーボードのDを2回押す
- Notebookの保存: command + s(右上にcheckpoint createdと表示される)
Pythonではじめる機械学習
- Anaconda
- NumPy : ナンパイ
- SciPy : サイパイ
- matplotlib : マットプロットリブ
- IPython : アイパイソン
- Jupyter Notebook : ジュパイター・ノートブック
- scikit-learn : サイキットラーン
- pandas : パンダス
- mglearn :
- TMP
Anaconda
大規模データ処理、予測解析、科学技術計算向けのPythonディストリビュージョン
含まれるライブラリ
- NumPy
- SciPy
- matplotlib
- IPython
- Jupyter Notebook
- scikit-learn
NumPy : ナンパイ
主な機能
クラス
ndarry : (n-dimensional)多次元配列
… 要素は全て同じ型
NumPy配列ndarrayのスライス : [start:stop:step]
import numpy as np l = list(range(10)) print(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(l[4:8]) # [4, 5, 6, 7] print(l[-5:-2]) # [5, 6, 7] print(l[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
データセットのロード
: データセットの読み込み
from sklearn.datasets import load_iris iris_dataset = load_iris() # irisオブジェクトは辞書に似たBunchクラスのオブジェクトでキーと値を持つ print("keys: {}".format(iris_dataset.keys())) type(iris_dataset['data']) # numpy.ndarray
shape
: ndarrayの構造を確認する
iris_dataset['data'].shape # (150, 4)
train_test_split
: 75%-25%でtrain-testデータを分ける
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( iris_dataset['data'], iris_dataset['target'], random_state=0)
SciPy : サイパイ
主な機能
- 高度な線形代数ルーチン
- 数学関数の最適化
- 信号処理
- 特殊な数学関数
- 統計分布
- 疎行列 : scipy.sparse
matplotlib : マットプロットリブ
主な機能
- グラフ描画ライブラリ
IPython : アイパイソン
Jupyter Notebook : ジュパイター・ノートブック
ブラウザベースのインタラクティブなプログラミング環境
scikit-learn : サイキットラーン
主な機能
- 機械学習のためのライブラリ
- NumPy,SciPyに依存する
- 入力をNumPy配列で受け取る
機械学習モデル
全てのscikit-learnの機械学習モデルは、Estimatorと総称される個別のクラスに実装される。
k-最近傍法(k-Nearest Neighbors : ニアリスト ネィボァ)のクラス分類アルゴリズムは、neighborsモジュールのKNeighborsClassifierクラスに実装されている。
KNeighborsClassifier
from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=1)
fit
訓練セットからモデルを構築する
knn.fit(X_train,y_train)
predict
予測する
X_new = np.array([[5,2.9,1,0.2]]) prediction = knn.predict(X_new) print(prediction) #[0] print("Predicted target name: {}".format( iris_dataset['target_names'][prediction])) # Predicted target name: ['setosa']
score
モデルの評価
y_pred = knn.predict(X_test) print(y_pred) # [2 1 0 2 0 2 0 1 1 1 2 1 1 1 1 0 1 1 0 0 2 1 0 0 2 0 0 1 1 0 2 1 0 2 2 1 0 2] # モデルの評価結果 print("Test set score: {:.2f}".format(np.mean(y_pred == y_test))) # Test set score: 0.97 print("Test set score: {:.2f}".format(knn.score(X_test,y_test))) # Test set score: 0.97
pandas : パンダス
主な機能
- データ変換、解析
- pandasのDataFrameはテーブルのようなもの
DataFrame
ndarrayをDataFrameに変換する
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
pd.plotting.scatter_matrix
pd.scatter_matrix
: ペアプロットを作成する関数
※ ペアプロット : 全ての組み合わせ可能な特微量の組み合わせをプロットする
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names) grr = pd.plotting.scatter_matrix(iris_dataframe, c= y_train, figsize=(15,15), marker='0', hist_kwds={'bins': 20}, s=60, alpha=.8, cmap=mglearn.cm3)
mglearn :
TMP
bunch
関数 topic
import
モジュールをインポートする。
import math print(type(math)) # <class 'module'> print(math) # <module 'math' from '/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/math.cpython-37m-darwin.so'>
from <モジュール名> import <オブジェクト名>でオブジェクトをインポートできる。
from math import pi print(pi) # 3.141592653589793 # 他のオブジェクトを使用しようとするとエラーNameErrorになる。 # print(math.radians(180)) # NameError: name 'math' is not defined
組み込み関数
関数オブジェクト
def hello(): print("ハロー") h = hello # 関数を変数に代入 h() # 関数オプジェクトを実行
- 引数に関数オブジェクトを渡す
def do(func): func() def hello(): print("ハロー") def bye(): print("バイバイ") h2 = hello do(h2) # 変数(関数オブジェクト)で渡す # ハロー do(bye) # 関数のまま渡す # バイバイ
クロージャ(関数閉包)
- 関数の中に関数を定義する
戻り値に関数を返す
# クロージャの定義 def charge(price) : # 関数の実態 def calc(num) : return price * num return calc # クロージャ(関数オブジェクト)を2種類作る child = charge(400) # 子供料金400円 adult = charge(1000) # 大人料金1000円 # 料金を計算する price1 = child(3) # 子供3人 price2 = adult(2) # 大人2人 print(price1) # 1200 print(price2) # 2000
無名関数(ラムダ式)
lambda 引数, 引数,... : 実行するステートメント
func = lambda w, h : w * h num = func(3, 4) print(num) # 12
ラムダ式を直接実行
num = (lambda w, h: w * h)(3, 4) print(num) # 12
map(関数, イテラブル)
イテラブルの要素を関数に渡し、戻りをmapに格納する
def double(x) : return x * 2 nums = [4, 3, 7, 6, 2, 1] nums2 = map(double, nums) print(nums2) # <map object at 0x1071661d0> print(list(nums2)) # mapはlist()で変換できる # [8, 6, 14, 12, 4, 2]
- map()の関数にラムダ式を使う
nums = [4, 3, 7, 6, 2, 1] nums2 = map(lambda n : n * 2, nums) print(list(nums2)) # [8, 6, 14, 12, 4, 2]
- リストの内包表記で同一のロジックが書ける
nums = [4, 3, 7, 6, 2, 1] nums3 = [n * 2 for n in nums] print(nums3) # [8, 6, 14, 12, 4, 2]
filter(boolを返す関数 ,イテラブル)
- filter()を使って正の値だけを抜き出したリストを作る
nums = [4, -3, 9, 1, -2, -4, 5] nums2 = filter(lambda x : x>0, nums) # 関数をラムダ式で記述 print(nums2) # <filter object at 0x10f017ef0> print(list(nums2)) # [4, 9, 1, 5]
- リストの内包表記で同一のロジックが書ける
nums = [4, -3, 9, 1, -2, -4, 5] nums2 = [n for n in nums if n > 0] print(nums2) # [4, 9, 1, 5]
イテレータとジェネレータ
イテレータは要素を1つづつ取り出せるオブジェクト
(イテラブルなオブジェクトとは違い、呼び出し場所が自由)
ジェネレータ関数はイテレータ(イテレータのように要素を取り出せるオブジェクト)をつくる関数
イテラブルからイテレータをつくる : iter(イテラブル)
colors = ["red", "blue", "green"] colors_iter = iter(colors) print(colors_iter) # <list_iterator object at 0x10e301f98> print(next(colors_iter)) # イテレータの次の要素を取り出す # red print(next(colors_iter)) # blue print(next(colors_iter)) # green print(next(colors_iter)) # Traceback (most recent call last): # イテレータが空なのでエラーになる # File "/test_def_topic.py", line 61, in <module> # print(next(colors_iter)) # StopIteration
ジェネレータ関数でイテレータをつくる
def menu_generator() : yield "ワイン" # ジェネレータの戻りはyeild(イールド) yield "サラダ" yield "スープ" yield "ステーキ" yield "アイスクリーム" menu = menu_generator() # ジェネレータ関数でmenuジェネレータをつくる print(type(menu)) # <class 'generator'> print(next(menu)) # ワイン
ジェネレータオブジェクトをfor-inで回す
def menu_generator() : yield "ワイン" # ジェネレータの戻りはyeild(イールド) yield "サラダ" yield "スープ" yield "ステーキ" yield "アイスクリーム" menu = menu_generator() for n in menu: print(n) # ワイン # サラダ # スープ # ステーキ # アイスクリーム
ループのジェネレータ関数
def num_generator() : n = 0 while True : # ループにしとく num = n*n + 1 # 数列式 num = yield num n += 1 gen = num_generator() # ジェネレータを作る for i in range(0, 5) : print(next(gen)) # ジェネレータから次の値を取り出す # 1 # 2 # 5 # 10 # 17
ジェネレータ式
内包表記と似ている
odd_gen = (odd for odd in range(1, 6, 2)) # ()で囲む print(next(odd_gen)) # 1 print(next(odd_gen)) # 3
ジェネレータに値を送る : send(値)
def testgen() : n = 0 while True : received = yield n # send()の値が入る if received : n = received else : n = n + 1 # nがnext()で取り出される gen = testgen() # ジェネレータをつくる print(next(gen)) # 0 print(next(gen)) # 1 print(gen.send(10)) # ジェネレータに値を送る # 10 print(next(gen)) # 11
サブジェネレータ(サブイテレータ)
サブジェネレータ : yield from ジェネレータ
サブイテレータ : yield from イテラブル
def main_gen(n): # メインのジェネレータ yield "start" yield from range(n, 0, -1) # サブイテレータから値を作る yield from "abc" # サブイテレータから値を作る yield from [10, 20, 30] # サブイテレータから値を作る yield from sub_gen() # サブジェネレータから値を作る yield "end" # サブジェネレータ def sub_gen(): yield "X" yield "Y" yield "Z" m = main_gen(3) print(list(m)) # ['start', 3, 2, 1, 'a', 'b', 'c', 10, 20, 30, 'X', 'Y', 'Z', 'end']
ユーザー定義関数
ユーザー定義関数
関数は、呼び出し元より上に記述する
- 基本構文
- 初期値のある引数
- 初期値のある関数にキーワード引数で値を渡す
- 引数の数を固定しない : *args
- キーワード引数を辞書で受取る : **kwargs
- 他のPythonファイルを読み込む (stdin利用)
基本構文
def sum(a, b) : x = a + b return x print(sum(2, 3)) # 5
初期値のある引数
def sum(a, b = 10) : # 初期値は後方から必須 x = a + b return x print(sum(2)) # 位置引数で渡す # 12 print(sum(2, 100)) # 102
初期値のある関数にキーワード引数で値を渡す
def sum(first = 10, second = 5) : # 初期値は後方から必須 x = first + second return x print(sum()) # 引数の省略 # 15 print(sum(second = 1)) # 第二引数のみキーワードで渡す # 11 print(sum(first=2)) # 7
引数の数を固定しない : *args
- *argsと書くのは慣例
def letters(*args) : # タプルで受け取る print(args) letters("apple", "cherry", "pine", "banana") # ('apple', 'cherry', 'pine', 'banana')
- 必須の固定引数と数を固定しない引数
def letters2(start, end, *args) : # タプルで受け取る print(f"{start},---") for t in args: print(f"args:{t}") print(f"---{end}") letters2("初めて", "終わり", "cherry", "pine", "banana") # 初めて,--- # args:cherry # args:pine # args:banana # ---終わり
キーワード引数を辞書で受取る : **kwargs
def fruit(**kwarfs): print(kwarfs) fruit(apple = 2, orange = 3, banana = 1) # キーワードでの辞書 # {'apple': 2, 'orange': 3, 'banana': 1}
他のPythonファイルを読み込む (stdin利用)
- 自前のファイル(値の平均を返す)
def average_calc(*args): # tupleで可変長を受ける if args: # argsが空でない l = [int(n) for n in args[0]] # stdinは文字列の為、変換 av = sum(l) / len(l) return av else: pass # TODO passは慣例 return None
- 自前のファイルをimportする
- コマンドラインから引数を受け取る
import average # 自前のファイル import sys a = average.average_calc(sys.argv[1:]) # コマンドラインから引数を受ける(リスト:スライス) print(a)
$ python test_def2.py 10 20 # スペースで引数を渡す # 15 # 結果
dict
dict: key:値
キーは重複不可で文字列・数値・タプル等のimmutableな値
要素に順序はない
{} でつくるのはsetと同じ
in での存在チェックや
- dict: key:値
- 初期化
- 初期化 : dict(key:値, key:値,...)
- 2つのリストからzipで辞書を作成
- イテレータと値の初期値で辞書をつくる : dist.fromkeys(イテレータ, 初期値)
- 要素の追加 : 辞書[キー] = 値
- 要素の追加(要素が無い時のみ) : setdefault(キー, 値)
- 要素の取得
- 他の辞書で更新 : update(辞書)
- 要素の削除
- pop(キー)
- 辞書内包表記 : {キー:値 for キー in イテラブル}
初期化
metro = { "G": "銀座線", # コメント "M": "丸ノ内線", "H": "日比谷線", "T": "東西線" } print(metro) # {'G': '銀座線', 'M': '丸ノ内線', 'H': '日比谷線', 'T': '東西線'}
初期化 : dict(key:値, key:値,...)
- タプルのリストを引数にして辞書を生成できる
data = dict([("yellow", 3), ("blue", 6), ("green", 5)]) print(data) # {'yellow': 3, 'blue': 6, 'green': 5}
- リストのタプルを引数にして辞書を生成できる
data = dict((["yellow", 3], ["blue", 6], ["green", 5])) print(data) # {'yellow': 3, 'blue': 6, 'green': 5}
- キーワード引数で辞書を生成できる
data = dict(yellow = 3, blue = 6, green = 7) print(data) # {'yellow': 3, 'blue': 6, 'green': 7} # キーが文字列になる
2つのリストからzipで辞書を作成
- キーと値のペアは少ない方で合わせられる
- キーの重複がある場合、後方優位
keys = ["yellow", "blue", "green", "blue", "red"] # redはペアがない為、無視される values = [3, 6, 5, 1] # blueのペアは後方優位で1 data = dict(zip(keys, values)) print(data) # {'yellow': 3, 'blue': 1, 'green': 5}
イテレータと値の初期値で辞書をつくる : dist.fromkeys(イテレータ, 初期値)
l = ["S", "M", "L"] d = dict.fromkeys(l, 0) # イテレータがkeyになる print(d) # {'S': 0, 'M': 0, 'L': 0} d2 = dict.fromkeys(l) # 初期値は省略可能 print(d2) # {'S': None, 'M': None, 'L': None}
- 同じ構造の辞書を作成
d = {'S': 1, 'M': 2, 'L': 3} d2 = dict.fromkeys(d, 0) print(d2)
要素の追加 : 辞書[キー] = 値
- キーがあれば更新、無ければ追加
data = {"yellow" : 3, "blue" : 6, "green" : 5} data["blue"] = 66 # 更新 print(data) # {'yellow': 3, 'blue': 66, 'green': 5} data["red"] = 22 # 追加 print(data) # {'yellow': 3, 'blue': 66, 'green': 5, 'red': 22}
要素の追加(要素が無い時のみ) : setdefault(キー, 値)
data = {"yellow" : 3, "blue" : 6, "green" : 5} a = data.setdefault("blue", 66) print(a) # ある時は既存の値を返す # 6 print(data) # ある時は更新されない # {'yellow': 3, 'blue': 6, 'green': 5} b = data.setdefault("white", 13) print(b) # 無い時はセットする値を返す # 13 print(data) # ある時は更新される # {'yellow': 3, 'blue': 6, 'green': 5, 'white': 13}
要素の取得
- キーで値を取得(リスト、タプルと同じ)
d = {'S': 1, 'M': 2, 'L': 3} try : print(d["M"]) # キーがないとエラーになる # 2 except KeyError: print("error")
- キーで値を取得 : get(キー)
d = {'S': 1, 'M': 2, 'L': 3} print(d.get("LL")) # get()はなくてもエラーにならない # None
- キーをリストで取得
d = {'S': 1, 'M': 2, 'L': 3} l = list(d.keys()) print(l) # ['S', 'M', 'L']
- 値をリストで取得
d = {'S': 1, 'M': 2, 'L': 3} l = list(d.values()) print(l) # [1, 2, 3]
- 要素(キー、値)をリストで取得
d = {'S': 1, 'M': 2, 'L': 3} l = d.items() print(l) # dict_items([('S', 1), ('M', 2), ('L', 3)]) for key, value in d.items(): # 要素をループで回す print(key, "&", value) # S & 1 # M & 2 # L & 3
他の辞書で更新 : update(辞書)
- 重複キーは無視、値は後方優位
data = {"yellow" : 3, "blue" : 6, "green" : 5} data2 = {"blue" : 16, "red" : 10} data.update(data2) print(data) # {'yellow': 3, 'blue': 16, 'green': 5, 'red': 10}
要素の削除
- キーを指定削除
data = {"yellow" : 3, "blue" : 6, "green" : 5, "red" : 9} del data["blue"] print(data) # {'yellow': 3, 'green': 5, 'red': 9}
- 全ての要素を削除
data.clear() print(data) # {}
pop(キー)
d = {'S': 1, 'M': 2, 'L': 3} a = d.pop("S") print(a) # 1 print(d) # {'M': 2, 'L': 3}
辞書内包表記 : {キー:値 for キー in イテラブル}
from random import randint data = ["yellow", "blue", "green", "red"] d = {key : randint(1,100) for key in data} print(d) # {'yellow': 53, 'blue': 68, 'green': 47, 'red': 7}
set
set: 集合演算ができる
値の重複不可能
mutableなオブジェクト
要素の順を持たない
in での存在チェックや、内包表記はリストと同じ
== での比較はリストと同じだが、順序は見ない
基本構文
初期化
a = {"bb", "cc", "aa"} print(a) # {'cc', 'bb', 'aa'}
初期化 : set(値, 値,...)
s = set(range(5, 10)) print(s) # (5, 6, 7, 8, 9)
リストの重複を削除
l = [1, 2, 3, 4, 5, 1, 2] s = set(l) # setは重複を除外する print(s) # {1, 2, 3, 4, 5} l = list(s) print(l) # [1, 2, 3, 4, 5]
要素の追加 : add(値) / 削除 : remove(値)
x = set() # 空のset作成 x.add("banana") x.add("pine") x.add("cherry") print(x) # {'cherry', 'pine', 'banana'} # 順不同 x.remove("pine") # 要素がない場合、エラー print(x) # {'cherry', 'banana'}
削除 : discard(要素がなくてもエラーにならない)
a = {"aa", "bb", "cc"} a.discard("dd") print(a) # {'aa', 'cc', 'bb'} a.discard("bb") print(a) # {'aa', 'cc'}
setを空にする : clear()
a = {"aa", "bb", "cc"} print(a) # a = {'bb', 'aa', 'cc'} a.clear() print(a) # set()
pop(値)
a = {"aa", "bb", "cc"} x = a.pop() print(a) # {'aa', 'cc'} print(x) # bb # 取れる値はランダム
変更不可のfrozenset(値,値,...)
data = frozenset(["aa", "bb", "cc"]) print(data) # frozenset({'aa', 'bb', 'cc'}) print(type(data)) # <class 'frozenset'>
リストからsetの内包表記 : {式 for 値 in イテラブル if 条件式}
numbers = [-1.3, 1.2, -1.2, 1.1, 1.5, -1.1, 1.2, 1.1, 1.4] num_set = {num for num in numbers if num > 0} # リストから重複削除、整数のセット print(num_set) # {1.2, 1.4, 1.1, 1.5}
集合演算
演算子(|, &, -, ^)はset同士でないと使えないが、 union(), intersection(), difference(), symmentric_difference() はイテラブルであれば使える
和集合: union(): |
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = {"パイナップル", "スイカ"} d = a | b | c print(d) # {'スイカ', 'パイナップル', 'リンゴ', 'みかん'} e = ["いちご", "パイナップル"] # リスト f = ("バナナ", "みかん") # タプル mix = d.union(e, f) print(mix) # {'スイカ', 'パイナップル', 'リンゴ', 'バナナ', 'みかん', 'いちご'}
積集合: intersection(): &
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = {"パイナップル", "みかん", "スイカ"} d = a & b & c print(d) # {'みかん'} a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = {"パイナップル", "みかん", "スイカ"} d = a.intersection(b, c) print(d) # {'みかん'}
差集合: difference(): -
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = a - b print(c) # {'リンゴ'} a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = a.difference(b) print(c) # {'リンゴ'}
対称差集合: symmetric_difference(): ^
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = a ^ b print(c) # {'リンゴ', 'スイカ'} a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = a.symmetric_difference(b) print(c) # {'リンゴ', 'スイカ'}
代入複合演子
セット値を更新する為、frozensetには使えない
和集合で更新 : update(set,set,...) : |=
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = {"パイナップル", "スイカ"} a.update(b, c) print(a) # {'みかん', 'パイナップル', 'スイカ', 'リンゴ'} a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = {"パイナップル", "スイカ"} a |= b a |= c print(a) # {'みかん', 'パイナップル', 'スイカ', 'リンゴ'}
積集合で更新: intersection_update(): &=
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = {"パイナップル", "みかん", "スイカ"} a.intersection_update(b, c) print(a) # {'みかん'} a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} c = {"パイナップル", "みかん", "スイカ"} a &= b a &= c print(a) # {'みかん'}
差集合で更新: difference_update(): -=
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} a.difference_update(b) print(a) # {'リンゴ'} a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} a -= b print(a) # {'リンゴ'}
対称差集合で更新: symmetric_difference_update(): ^=
a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} a.symmetric_difference_update(b) print(a) # {'リンゴ', 'スイカ'} a = {"リンゴ", "みかん"} b = {"みかん", "スイカ"} a ^= b print(a) # {'リンゴ', 'スイカ'}
要素の比較
全ての要素の比較(順不同) : == / !=
a = {"aa", "bb", "cc"} b = {"aa", "bb", "cc"} c = {"aa", "bb", "dd"} print(a == b) # True print(a != c) # True
共通要素が1つもない : isdisjoint()
a = {"aa", "bb", "cc"} b = {"x", "bb", "y"} c = {"o", "p", "q"} print(a.isdisjoint(b)) # "bb"が一致している # False print(a.isdisjoint(c)) # 1つも一致していない # True
部分集合(サブセット) : issubset(set) : <=
同値でもTrueになる
a = {"red", "blue"} b = {"blue", "green", "red", "pink"} print(a.issubset(b)) # True print(a <= b) # True
上位集合(スーパーセット) : issuperset(set) : >=
a = {"blue", "green", "red", "pink"} b = {"red", "blue"} print(a.issuperset(b)) # True print(a >= b) # True
tuple
tuple: 値の重複が可能
immutableなオブジェクトの為、辞書のキーに利用可能
in での存在チェックや、max()、 == / is での比較はリストと同じ
()で囲ってもtuple内包表記にならず、ジェネレータ式になる
初期化
numbers = (4, 8, 15, 16, 23, 42) print(numbers) # (4, 8, 15, 16, 23, 42)
初期化 : tuple(値,値,...)
tuple : 組み込み関数
t = tuple(range(5,10)) print(t) # (5, 6, 7, 8, 9) t = tuple("月火水木金土日") print(t) # ('月', '火', '水', '木', '金', '土', '日') a = [1, 2, 3, 4] # リストをタプルへ tu = tuple(a) print(tu) # (1, 2, 3, 4)
結合
a = (4, 8, 15,) b = (16, 23, 42,) c = a + b + (99,) # 1つの場合は、,をつけることが必須 print(c) # (4, 8, 15, 16, 23, 42, 99)
# スライス [開始位置:終了位置:ステップ]
変数で受け取った場合、copyと同じく値コピーとなる為、ポインタは変わる
foods = ("apple", "banana", "pine", "cherry") print(foods[1:3]) # 終了位置はマイナス1 # ('banana', 'pine')
要素の取得
リストと同じ
data = (1, 2 ,3) print(data[0]) # 1
タプルのアンパック
(a, b) = ("100", "200") print(a) # 100 print(b) # 200
複数リストをzipでまとめる
要素はタプルになる
name1 = ["鈴木", "田中", "松本"] name2 = ["イチロー", "圭", "仁志"] t = zip(name1, name2) l = list(t) print(l) # [('鈴木', 'イチロー'), ('田中', '圭'), ('松本', '仁志')]
list
list: 値の重複が可能
mutableなオブジェクト
- list: 値の重複が可能
- 初期化
- listへ型変換 : list()
- 要素の取得
- 要素の挿入 : append(値)
- 要素の結合 : extend(リスト)
- 要素の挿入 : insert(挿入位置, 値)
- 取得と削除 : pop(削除位置)
- 値を指定して削除 : remove(値) / del(インデックス)
- スライス [開始位置:終了位置:ステップ]
- リストの比較 : == / is / is not
- カウンタ付きループ : enumerate(リスト, 開始値)
- 複数のリストをforで扱う : zip
- リスト内包表記 : [式 for in イテラブル]
- リスト内の検索 : in / index()
初期化
a = ["a", "b", "c", "d"] print(a) # ['a', 'b', 'c', 'd']
listへ型変換 : list()
b = list(range(1, 10)) # 組み込み関数:list() print(b) # [1, 2, 3, 4, 5, 6, 7, 8, 9] t = ("aa", "bb", "cc") # タプルをリストへ c = list(t) print(c) # ['aa', 'bb', 'cc']
要素の取得
data = [1, 2 ,3] print(data[0]) # 1
要素の挿入 : append(値)
data = [1, 2 ,3] data.append(4) # 1つの要素を末尾に追加 print(data) # [1, 2, 3, 4]
要素の結合 : extend(リスト)
data = [1, 2 ,3] data = data + [10, 11] # 複数の時 print(data) # [1, 2, 3, 10, 11] data.extend([20, 21]) print(data) # [1, 2, 3, 10, 11, 20, 21] data += [30, 31] print(data) # [1, 2, 3, 10, 11, 20, 21]
要素の挿入 : insert(挿入位置, 値)
data = [1, 2 ,3] data.insert(1, "new") print(data) # [1, 'new', 2, 3]
取得と削除 : pop(削除位置)
data = [1, 2, 3, 4, 5, 6, 7, 8] a = data.pop() # 引数を省略すると末尾を削除 print(data) # [1, 2, 3, 4, 5, 6, 7] print(a) # 8 data.pop(1) print(data) # [1, 3, 4, 5, 6, 7]
値を指定して削除 : remove(値) / del(インデックス)
colors = ["red", "blue", "yellow", "black", "blue"] if "blue" in colors: # inで存在チェックをし、boolを返す colors.remove("blue") # 削除されるのは1つ。全て削除したい場合はループさせる。 print(colors) # ['red', 'yellow', 'black']
スライス [開始位置:終了位置:ステップ]
変数で受け取った場合、copyと同じく値コピーとなる為、ポインタは変わる
foods = ["apple", "banana", "pine", "cherry"] print(foods[1:3]) # 終了位置はマイナス1 # ['banana', 'pine']
リストの比較 : == / is / is not
foods = ["apple", "banana", "pine"] foods2 = ["apple", "banana", "pine"] foods3 = ["apple", "banana", "cherry"] foods4 = foods print(foods == foods2) # =:要素の一致(並び順も) # True print(foods == foods3) # False print(foods is foods2) # is:ポインタの一致 # False print(foods is foods4) # True print(foods is not foods4) # False foods.append("orange") print(foods4) # ['apple', 'banana', 'pine', 'orange'] foods5 = foods4.copy() # copyは値コピー print(foods5 is foods4) # False
カウンタ付きループ : enumerate(リスト, 開始値)
enumerate() : 組み込み関数 names = ["鈴木", "田中", "佐藤", "木村"] for i, name in enumerate(names,1): print(f"{i}: {name}") # 1: 鈴木 # 2: 田中 # 3: 佐藤 # 4: 木村
複数のリストをforで扱う : zip
names = ["鈴木", "田中", "佐藤", "木村"] names2 = ["つとむ", "あい", "ゆい", "あすか"] long_names = list() for name1, name2 in zip(names, names2): long_names.append(name1 + name2) print(long_names) # ['鈴木つとむ', '田中あい', '佐藤ゆい', '木村あすか']
リスト内包表記 : [式 for in イテラブル]
条件付きリスト内包表記 : [式 for in イテラブル if 条件式]
[]の中に for in を書き、イテラブルなオブジェクトから新しいリストを生成する
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers2 = [num**2 for num in numbers if num%2 == 0] # 偶数のみ2乗してリスト print(numbers2) # [4, 16, 36, 64, 100]
リスト内の検索 : in / index()
colors = ["red", "blue", "yellow", "black", "blue"] print("yellow" in colors) # True print(colors.index("black")) # 3
組み込み関数
組み込み関数:importしなくとも使える関数
- print(値1, 値2,..., sep = "区切り文字", end = "行末文字")
- type(変数)
- 型変換
- max(数値1, 数値2,...) / min(数値1, 数値2,...)
- len(イテラブル)
- round(数値, 桁数)
- input("表示文字列")
- range( 開始値, 終了値, ステップ)
- isinstance(変数, (type, type,...))
- リスト内の検索 : in / index()
print(値1, 値2,..., sep = "区切り文字", end = "行末文字")
a = 100 b = 200 c = 300 abc = a + b + c print(a, b, c, sep = "、", end = "/以上") print(abc) # 100、200、300/以上600
type(変数)
a = "test" print(type(a)) # <class 'str'> b = 123 print(type(b)) # <class 'int'> c = 0.123 print(type(c)) # <class 'float'> d = True print(type(d)) # <class 'bool'> e = [a,b,c] print(type(e)) # <class 'list'> f = (a,b,c) print(type(f)) # <class 'tuple'> g = {a,b,c} print(type(g)) # <class 'set'> h = {1:"aa", 2:"bb"} print(type(h)) # <class 'dict'>
型変換
a = 123 print("string:" + str(a)) # stringにintのままでは接続できない b = "456" print(1000 + int(b))
max(数値1, 数値2,...) / min(数値1, 数値2,...)
print(max(1, 9, 3, 6.3)) # 9 print(min(1, 9, 3, 6.3)) # 1
len(イテラブル)
print(len("テスト123")) # 6 list = ["aa", "bb", "cc", "dd"] print(len(list)) # 4
round(数値, 桁数)
print(round(100.3)) # 100 print(round(100.5)) # 5は切捨て # 100 print(round(100.876, 2)) # 100.88
input("表示文字列")
t = input("入力して下さい") print(t + "!!!") # 入力して下さい # "{入力文字}!!!"
range( 開始値, 終了値, ステップ)
for i in range(10, 20, 2): # 終了値は19になる print(i) # 10 # 12 # 14 # 16 # 18
isinstance(変数, (type, type,...))
a = "test" b = 12.3 print(isinstance(a,(int,float))) # False print(isinstance(b,(int,float))) # True
リスト内の検索 : in / index()
colors = ["red", "blue", "yellow", "black", "blue"] print("yellow" in colors) # True print(colors.index("black")) # 3
Pycharm shortcut-key
実行
アクティブファイルの実行
ctrl + r
ファイルを選択して実行
ctrl + opt + r
編集
オートフォーマット
cmd + opt + l
処理系 ( if, while, for, try, comment )
if
from random import randint a = randint(0, 100) if a == 100: print(str(a) + "は10と等しい") # インデントを揃える print("if true 処理") # インデントを揃える elif a > 50: print(str(a) + "は50より大きい") print("else-if true 処理") else: print(str(a) + "は100と等しくもなく、大きくもない") # true処理のインデントと揃える print("else 処理") print("- next process -")
while
from random import randint numbers = [] while len(numbers) < 10: # numbersが10個になるまで繰り返す。途中でマイナスが出た場合はbreak n = randint(-10, 90) # -10~90の乱数 if n < 0: print(str(n) + "はマイナスの為、break") break if n in numbers: continue numbers.append(n) else: print("10個リストを作成できた " + str(numbers))
for
指定回数ループ
for i in range(10, 20, 3): # range(開始値, 終了値, ステップ) print(i) # 10 # 13 # 16 # 19
リスト分ループ
numlist = [3, 4.2, 10, "x", 1, 9] sum = 0 for num in numlist: if not isinstance(num, (int, float)): # インスタンスの型チェック print(num, " は数値でない為、break") break sum += num print(num, "/", sum) else: print("breakされなかった時のみ、elseへ") # breakのあるfor文のみ意味を持つ
カウンタ付きループ : enumerate(リスト, 開始値)
enumerate() : 組み込み関数 names = ["鈴木", "田中", "佐藤", "木村"] for i, name in enumerate(names,1): print(f"{i}: {name}") # 1: 鈴木 # 2: 田中 # 3: 佐藤 # 4: 木村
try-except
sum = 8000 while True: num = input("人数を入力して下さい(qで終了)") if num == "q": print("終了しました") break try: price = round(sum / int(num)) if price < 0: continue print("1人あたりの金額 ", price) except ZeroDivisionError as error: # エラーの種類でキャッチ。tryの中のみerror変数でエラー内容を参照可能 print("0以外を入力して下さい") print(error) # エラー内容を参照 except : # エラー種別を指定しない場合、asは使えない print("その他のエラー") else: print("try句で例外のない時のみ実行")
コメント
kosu = 12 * 5 # This is comment print(kosu) kosu2 = kosu + 1 """ this is comment """ print(kosu2)
Python 初期設定
Anaconda & Pycharm
Python terminal memo
terminalでバージョン確認
python
Pythonを終了する
exit() # ctrl + d
ファイルの実行
python {ファイル名}.py
コマンドライン引数
python test.py a b 10
import sys args = sys.argv print(args) # ['test.py', 'a', 'b', 'c'] # 第0引数はファイル名 print("第1引数:" + args[1]) # 第1引数:a print("第2引数:" + args[2]) # 第2引数:b print("第3引数:" + args[3]) # 第3引数:10 # string
Jupyter Notebook を起動する
jupyter notebook
category Python
category Python
IntelliJ shortcut
編集
// ★★★ テンプレートを開く : Ctrl + J
// ★★★ リファクタリングメニュー表示 : Ctrl + Alt + Shift + T
// ★★★ Scratch : Ctrl + Shift + Alt + Insert
// if、while、forなどで囲む : Ctrl + Alt + T
// マルチカーソル : 特定文字列を選択してから Alt + J
// コピー履歴から貼り付け : Ctrl + Shift + V
// リネーム : Shift + F6
// 現在の行を複製 : Ctrl + D
// 現在の行を削除 : Ctrl + Y
// 選択行を上下に移動 : Alt + Shift + ↑/↓
// imports編成 : Ctrl + Alt + O
// auto format : Ctrl + Alt + L
// 選択状態ブロックの拡大/縮小 : Ctrl + W / Ctrl + Shift + W移動
// 宣言へジャンプ : Ctrl + B
// 変数が使われている箇所へジャンプ : Ctrl + Alt + F7
// ★★★ 呼び出し先を調べる : Alt + Ctrl + H
// 戻る : Alt + Ctrl + ←/→
// プロジェクトツールウィンドウの表示/非表示 : Alt + 1
// 最近開いたファイルを表示 : Ctrl + E検索
// ファイル横断テキスト検索 : Ctrl + Shift + F
// なんでも検索 : Shift 2回連打
// コマンド検索 : Ctrl + Shift + A