■Python 3.4.3 | Top |
0.実行環境の構築
1.文字列
2.数値型
3.日付型
4.列挙型
5.共用体型
6.定数
7.let
10.タプル
11.集合( set型 )
12.条件分岐
13.ループ
14.例外処理
15.with
16.関数
17.クラス
19.バッチ処理
20.内包表記
21.正規表現
22.pickleモジュール
23.pycodestyle
24.flake8
実行環境の構築
1.※pythonのインストールは完了している前提。 2.venv仮想環境の構築 各モジュールのバージョンを仮想環境ごとに分けて管理できるようにする。
※以下macosの場合 1)terminalを起動する。 2)仮想環境を構築するディレクトリに移動する 3)python -m venv jupyter-venv ※jupyter-venvは構築した仮想環境のフォルダ名 4)source jupyter-venv/bin/activate ※仮想環境が実行する 5)deactivate ※仮想環境を停止する 6)rm -r jupyter-venv ※作成した仮想環境を削除する 3.ipython 対話モード 1)pip3 install ipython 2)ipython ※対話モードで起動する。 3)quit() ※対話モードを終了する。
4.jupyter notebook 1)pip3 install jupyter notebook 2)jupyter notebook
文字列型の宣言
Python では型が存在しない。初期値を代入することによって変数の宣言となる。
str = "abc" print(str) # "abc" str = 'def' print(str) # 'def' str = """ abc def """ print( str ) # abc # def
文字列長
現在の文字列内の文字数を取得する。
str = "abc" print( len( str ) ) # 3 str = "あいう" print( len( str ) ) # 3
Python 言語リファレンス
文字コードを指定してバイト単位で桁数を取得する。
文字列の連結
+ で連結する
print( "abc" + "def" ) # "abcdef" str = "abc" str += "def" print( str ) # "abcdef"
イテラブル iterable 中の文字列を結合した文字列を返す。 iterable に bytes オブジェクトのような非文字列の値が存在するなら、 TypeError が送出される。要素間のセパレータは、このメソッドを提供する文字列である。
sep = "-" print( sep.join( ["abc", "def", "ghi"] ) ) # abc-def-ghi
文字列の分割
引数の文字に基づいて文字列をリストに分割する。区切り文字が見つからない場合は元の文字列を返す。
str = "abc def/ghe." print( str.split("def") ) # ['abc ', '/ghe.'] print( str.split("xyz") ) # ['abc def/ghe.'] # 1文字ずつバラス print( list(str) ) # ['a', 'b', 'c', ' ', 'd', 'e', 'f', '/', 'g', 'h', 'e', '.']
Python 言語リファレンス
文字列を sep の最初の出現位置で区切り、 3 要素のタプルを返す。タプルの内容は、区切りの前の部分、区切り文字列そのもの、そして区切りの後ろの部分。もし区切れなければ、タプルには元の文字列そのものとその後ろに二つの空文字列が入る。
str = "abc def ghe." print( str.partition(" ") ) # ('abc', ' ', 'def ghe.') print( str.partition("/") ) # ('abc def ghe.', '', '')
Python 言語リファレンス
文字列を改行部分で分解し、各行からなるリストを返す。 keepends に真が与えらない限り、返されるリストに改行は含まれない。
str = "abc\rdef\nghi\r\nlmn" print( str.splitlines(False) ) # ['abc', 'def', 'ghi', 'lmn'] print( str.splitlines(True) ) # ['abc\r', 'def\n', 'ghi\r\n', 'lmn'] str = "abc" print( str.splitlines(False) ) # ['abc']
Python 言語リファレンス
正規表現による文字列分割
文字列リストの結合
セパレータを指定して文字列リストを結合する
print( ','.join(['a', 'b', 'c'])) # a,b,c print( ''.join(['a', 'b', 'c'])) # abc print( ''.join(['a'] * 3)) # aaa
文字列の置換
文字列をコピーし、現れる部分文字列 old 全てを new に置換して返す。オプション引数 count が与えられている場合、先頭から count 個の old だけを置換する。
str = "abc/def/abc/def/ABC" print( str.replace("abc", "XYZ") ) # "XYZ/def/XYZ/def/ABC" print( str.replace("DEF", "xyz") ) # "abc/def/abc/def/ABC"
Python 言語リファレンス
文字列内の全てのタブ文字が 1 つ以上のスペースで置換された、文字列のコピーを返す。
str = "abc/def\tabc/def\tABC" print( str.expandtabs() ) # "abc/def abc/def ABC" print( str.expandtabs(3) ) # "abc/def abc/def ABC"
Python 言語リファレンス
文字列の挿入
str = 'abcdef' print( str[:3] + 'xyz' + str[3:] ) # "abcxyzdef"
文字列の削除
str = 'abcdef' print( str[:3] + str[4:] ) # "abcef"
部分文字列の取得
[ startIndex : endIndex ] 形式で部分文字列の取得を行う。endIndex は抽出対象の終端のインデックス位置で endIndex - 1 まで抽出される。
str = "abc/def/あいう/def/ABC" print( str[6] ) # "f" print( str[6:10] ) # "f/あい" print( str[6:] ) # "f/あいう/def/ABC" print( str[:5] ) # "abc/d" print( str[:-3] ) # "abc/def/あいう/def/" print( str[1:8:2] ) # "b/e/"
文字列比較
== で比較する。
# 大文字小文字区別して比較する print('abc' == 'abc') # True print('abc' == 'Abc') # False # 大文字小文字区別しないで比較する # casefold()は小文字に変換するのでlower()に似ているが、casefold()の場合特殊文字も小文字に変換できる print('abc'.casefold() == 'Abc'.casefold()) # True
文字列検索
現在の文字列に指定した文字または文字列が含まれているかの判定結果を True または False で返す。
str = "abc def/ghe." # 大文字小文字区別して判定する print("def" in str) # True print("Def" in str) # False # 大文字小文字区別しないで判定する print("Def".casefold() in str.casefold()) # True
現在の文字列の先頭が、指定した文字列と一致するかの判定結果を True または False で返す。
str = "abc def/ghe." # 大文字小文字区別して判定する。 print(str.startswith("abc")) # True print(str.startswith("ABC")) # False print(str.startswith("bc")) # False # 大文字小文字区別しないで判定する。 print(str.casefold().startswith("ABC".casefold())) # True
Python 言語リファレンス
現在の文字列の末尾が、指定した文字列と一致するかの判定結果を True または False で返す。
str = "abc def/ghe." # 大文字小文字区別して判定する。 print(str.endswith("ghe.")) # True print(str.endswith("Ghe.")) # False print(str.endswith("bc")) # False # 大文字小文字区別しないで判定する。 print(str.casefold().endswith("Ghe.".casefold())) # True
Python 言語リファレンス
文字列のスライス s[start:end] に sub が含まれる場合、その最小のインデックスを返す。sub が見つからなかった場合 -1 を返す。 end はインデックスを指定し、end - 1 までの範囲内で検索する。 大文字小文字区別して判定する。
str = "abcd efgh/abcd:abcd" print( str.find( "cd" ) ) # 2 print( str.find( "CD" ) ) # -1 # 指定したインデックス以降の文字列内で検索する print( str.find( "cd", 12 ) ) # 12 print( str.find( "ab", 17 ) ) # -1 print( str.find( "cd", 20 ) ) # -1( 例外にはならない ) # 指定した範囲内で検索する print( str.find( "cd", 12, 14 ) ) # 12 print( str.find( "cd", 13, 18 ) ) # -1 print( str.find( "ab", 17, 20 ) ) # -1( 例外にはならない )
Python 言語リファレンス
find() と同様だが、部分文字列が見つからなかったとき ValueError を送出する。
str = "abcd efgh/abcd:abcd" print( str.index( "cd" ) ) # 2 print( str.index( "CD" ) ) # 例外発生!! # 指定したインデックス以降の文字列内で検索する print( str.index( "cd", 12 ) ) # 12 print( str.index( "ab", 17 ) ) # 例外発生!! print( str.index( "cd", 20 ) ) # 例外発生!! # 指定した範囲内で検索する print( str.index( "cd", 12, 14 ) ) # 12 print( str.index( "cd", 13, 18 ) ) # 例外発生!! print( str.index( "ab", 17, 20 ) ) # 例外発生!!
Python 言語リファレンス
[start, end] の範囲に、部分文字列 sub が重複せず出現する回数を返す。end はインデックスを指定し、end - 1 までの範囲内で検索する。 大文字小文字区別する。
str = "abcd efgh/abcd:abcd" print( str.count( "abc" ) ) # 3 print( str.count( "ABC" ) ) # 0 # 指定したインデックス以降の文字列内で検索する print( str.count( "abc", 10 ) ) # 2 print( str.count( "abc", 11 ) ) # 1 print( str.count( "abc", 20 ) ) # 0 # 指定した範囲内で検索する print( str.count( "abc", 10, 13 ) ) # 1 print( str.count( "abc", 10, 12 ) ) # 0 print( str.count( "abc", 17, 20 ) ) # 0
Python 言語リファレンス
大文字変換
全ての大小文字の区別のある文字列が大文字に変換された、文字列のコピーを返す。
str = "ABC def/あいう." print( str.upper() ) # "ABC DEF/あいう."
Python 言語リファレンス
小文字変換
全ての大小文字の区別のある文字列が小文字に変換された、文字列のコピーを返す。
str = "ABC def/あいう." print( str.lower() ) # "abc def/あいう."
Python 言語リファレンス
最初の文字を大文字にし、残りを小文字にした文字列のコピーを返す。
str = "abc DEF/あいう." print( str.capitalize() ) # "Abc def/あいう."
Python 言語リファレンス
単語の先頭のみ大文字に変換する。
str = "abc DEF xyz." print( str.title() ) # "Abc Def Xyz."
Python 言語リファレンス
大文字が小文字に、小文字が大文字に変換された、文字列のコピーを返す。
str = "abc DEF/あいう." print( str.swapcase() ) # "ABC def/あいう."
Python 言語リファレンス
全角文字変換
半角文字変換
先頭および末尾の文字の削除
文字列の先頭および末尾部分を除去したコピーを返す。引数 chars は除去される文字集合を指定する文字列。 chars が省略されるか None の場合、空白文字が除去される。 chars 文字列は接頭語でも接尾語でもなく、そこに含まれる文字の組み合わせ全てが除去される。
str = " abc def/abc.アイウエオ " print( str.strip() ) # "abc def/abc.アイウエオ" # スペース以外の文字も除去できる print( str.strip(" abcエオ" ) ) # "def/abc.アイウ" # 先頭の文字だけ除去する print( str.lstrip() ) # "abc def/abc.アイウエオ " # 末尾の文字だけ除去する print( str.rstrip() ) # " abc def/abc.アイウエオ"
Python 言語リファレンス
文字列の大小判定
<、 >、= 演算子を使用して文字列の大小判定を行う。
str1 = "abc" str2 = "def" str3 = "ABC" if str1 > "abc": print( "str1 > str2" ) elif str1 < "abc": print( "str1 < str2" ) else: print( "str1 = str2" ) if str1 > str2: print( "str1 > str2" ) elif str1 < str2: print( "str1 < str2" ) else: print( "str1 = str2" ) # 大文字小文字区別する if str1 > str3: print( "str1 > str3" ) elif str1 < str3: print( "str1 < str3" ) else: print( "str1 = str3" ) # str1 = str1 # str1 < str2 # str1 > str3
パディング
width の長さをもつ右寄せした文字列を返す。パディングには fillchar で指定された文字(デフォルトでは ASCII スペース)が使わる。 width が len(s) 以下の場合、元の文字列が返される。
str = "abc" print( str.rjust( 5 ) ) # " abc" print( str.rjust( 1 ) ) # "abc" print( str.rjust( 5, '?' ) ) # "??abc"
Python 言語リファレンス
長さ width の左揃えした文字列を返す。パディングは指定された fillchar (デフォルトでは ASCII スペース) を使って行われる。 width が len(s) 以下ならば、元の文字列が返される。
str = "abc" print( str.ljust( 5 ) ) # "abc " print( str.ljust( 1 ) ) # "abc" print( str.ljust( 5, '?' ) ) # "abc??"
Python 言語リファレンス
長さが width になるよう ASCII '0' で左詰めした文字列のコピーを返す。先頭が符号接頭辞 ('+'/'-') だった場合、 '0' は符号の前ではなく 後 に挿入される。width が len(s) 以下の場合元の文字列を返す。
str = "123" print( str.zfill( 5 ) ) # "00123" print( str.zfill( 1 ) ) # "123" str = "-123" print( str.zfill( 5 ) ) # "-0123"
Python 言語リファレンス
width の長さをもつ中央寄せされた文字列を返す。パディングには fillchar で指定された値 (デフォルトでは ASCII スペース) が使われる。 width が len(s) 以下なら元の文字列が返される。
str = "123" print( str.center( 5 ) ) # " 123 " print( str.center( 6 ) ) # " 123 " print( str.center( 1 ) ) # "123" print( str.center( 5, "?" ) ) # "?123?" str = "1234" print( str.center( 5 ) ) # " 1234" print( str.center( 6 ) ) # " 1234 "
Python 言語リファレンス
文字列型へ変換
数値型を表す文字列を返す。
print( str( 123 + 456 ) ) # "579"
Python 言語リファレンス
書式変換
文字列の書式化操作を行う。このメソッドを呼び出す文字列は通常の文字、または、 {} で区切られた置換フィールドを含む。 それぞれの置換フィールドは位置引数のインデックスナンバー、または、キーワード引数の名前を含む。 戻り値は、それぞれの置換フィールドが対応する引数の文字列値で置換された文字列のコピー。
str = "abc" a = 123 b = 456.789 c = 0xA9 # テンプレートリテラル print(f'{str}:{a}') # abc:123 print( "文字列編集:{0}, {1}, {0}, {2}。".format( str, a, b ) ) # "文字列編集:abc, 123, abc, 456.789。" # 日付 from datetime import datetime print( datetime.now().strftime( '%Y/%m/%d %H:%M:%S:%f' ) ) # "2015/10/10 10:36:40:190482" # 右揃えで文字列の幅を定義する print( "文字列編集:{0:>10}".format( str ) ) # "文字列編集: abc" # 左揃えで文字列の幅を定義する print( "文字列編集:{0:<10}".format( str ) ) # "文字列編集:abc " # 数値型を10進数で変換 print( "文字列編集:{0:d}".format( c ) ) # "文字列編集:169" # 数値型を16進数で変換 print( "文字列編集:{0:X}".format( a ) ) # "文字列編集:7B" # 数値型のZeroパディング print( "文字列編集:{0:>08}".format( a ) ) # "文字列編集:00000123" # 浮動小数の変換 print( "文字列編集:{0:.4f}".format( b ) ) # "文字列編集:456.7890" # 浮動小数の変換(切り捨てた分は四捨五入して丸め処理する) print( "文字列編集:{0:.2f}".format( b ) ) # "文字列編集:456.79"
Python 言語リファレンス
文字コード取得
文字列のエンコードされた16進数のバイト列として返す。標準のエンコーディングは 'utf-8'。
bits = "あいう".encode( "utf8" ) print(bits) # b'\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86' str = bits.decode( "utf8" ) print(str) # 'あいう'
Python 言語リファレンス
文字列を逆順に変換
str = 'abcdefg' print(''.join(sorted(list(str), reverse=True))) # 'gfedcba'
ASCIIコードと文字の相互変換
s = 'A' c = ord(s) print(c) # 65 s = chr(c) print(s) # A
文字判定
print(type('a') is str) # True print(type(1) is str) # False
数値型の宣言
num = 123 print( num ) # 123
四則演算
# 加算 print( 456 + 123 ) # 579 # 減算 print( 456 - 123 ) # 333 # 除算 print( 456 / 123 ) # 3.707317073170732 print( 456 / 0 ) # 実行時エラー # 乗算 print( 456 * 123 ) # 56088 # 余り print( 456 % 123 ) # 87 # 累乗 print( 4**2 ) # 16
数値変換
print( int('123', 10) + 10 ) # 133 print( int('0xAF', 16) + 10 ) # 185 print( int('a', 10) + 10 ) # 実行時エラー
リファレンス:Python 言語リファレンス
print( float('123') ) # 123.0 print( float('123.1') ) # 123.1 print( float('a') ) # 実行時エラー
リファレンス:Python 言語リファレンス
絶対値
引数として与えた数の絶対値を返す
import math print( abs(-3) ) # 3 print( math.fabs(1) ) # 1.0 print( math.fabs(-2) ) # 2.0 print( math.fabs('-1') ) # 実行時エラー
リファレンス:Python 言語リファレンス
切り上げ
引数として与えた数以上の最小の整数を返す
import math print( math.ceil(5.12) ) # 6 print( math.ceil(5.67 ) ) # 6 print( math.ceil(-5.12) ) # -5 print( math.ceil(-5.67) ) # -5
リファレンス:Python 言語リファレンス
切り下げ
引数として与えた数以下の最大の整数を返す
import math print( math.floor(5.12) ) # 5 print( math.floor(5.67 ) ) # 5 print( math.floor(-5.12) ) # -6 print( math.floor(-5.67) ) # -6
リファレンス:Python 言語リファレンス
最大値取得
iterable の中で最大の要素、または2つ以上の引数の中で最大のものを返します。
print( max( 20, 3, 4, 12 ) ) # 20 print( max( 'def', 'abc', 'ghi' ) ) # 'ghi'
リファレンス:Python 言語リファレンス
最小値取得
iterable の中で最小の要素、または2つ以上の引数の中で最小のものを返します。
print( min( 20, 3, 4, 12 ) ) # 3 print( min( 'def', 'abc', 'ghi' ) ) # 'abc'
リファレンス:Python 言語リファレンス
べき乗
x を y 乗した値を返す。
import math print( math.pow( 2, 4 ) ) # 16.0
リファレンス:Python 言語リファレンス
乱数
import random random.seed() # 乱数生成器を初期化する print( random.randint( 2, 10 ) ) # 2 〜 10 の整数 print( random.random() ) # 0.0 〜 1.0 の浮動小数点数
リファレンス:Python 言語リファレンス
丸め処理
引数として与えた数を銀行丸める(5の場合偶数になるように丸める)。
print( round(12.4) ) # 12 print( round(13.4) ) # 13 print( round(12.5) ) # 12 print( round(13.5) ) # 14
リファレンス:Python 言語リファレンス
四捨五入
print( int(12.4 + 0.5) ) # 12 print( int(12.5 + 0.5) ) # 13 print( int(12.6 + 0.5) ) # 13
平方根
引数として与えた数の平方根を返す。
import math print( math.sqrt(2) ) # 1.4142135623730951
リファレンス:Python 言語リファレンス
小数部と整数部の分割
x の小数部分と整数部分を返す。
import math print( math.modf(2.3) ) # (0.2999999999999998, 2.0)
リファレンス:Python 言語リファレンス
数値判定
print(type(-100) is int) # True print(type(-10.1) is float) # True print(type('-100') is int) # False print(type('-100.1') is float) # False
現在日時取得
from datetime import datetime print( datetime.now().strftime( '%Y/%m/%d %H:%M:%S' ) ) # "2015/10/10 10:36:40"
リファレンス:Python 言語リファレンス
任意の日付型を作成する
from datetime import datetime print( datetime( 2014, 2, 3, 12, 5, 7 ) ) # "2014-02-03 12:05:07" # 日付文字列をフォーマット指定して日付型に変換する d = datetime.strptime('2014年2月3日 12時5分7秒', '%Y年%m月%d日 %H時%M分%S秒') print(d) # 2014-02-03 12:05:07
現在の曜日を取得
指定された日時の「曜日」のインデックスを返す。月曜日が 0、火曜日が 1 ... となる。
from datetime import datetime weekdays = ( '月', '火', '水', '木', '金', '土', '日' ) print( weekdays[datetime.now().weekday()] ) # '火'
リファレンス:Python 言語リファレンス
日付の加減算
from datetime import datetime from datetime import timedelta now = datetime.now() # 日付加算 print( now + timedelta(days=30) ) # 現在の日時の30日後の日時を出力。有効な日を超える場合、月も更新される。 # 時間減算 print( now + timedelta(hours=-30) ) # 現在の日時の30時間前の日時を出力。時間が負の数となる場合、日も更新される。
リファレンス:Python 言語リファレンス
日付の大小比較
from datetime import datetime datetime1 = datetime.now() datetime2 = datetime( 2014, 2, 3, 12, 5, 7 ) if (datetime1 > datetime2): print('datetime1 > datetime2') elif (datetime1 < datetime2): print('datetime1 < datetime2') else: print('datetime1 = datetime2')
列挙型
from enum import Enum class Color(Enum): red = 1 green = 2 blue = 3 print( Color.red ) # Color.red print(repr(Color.red)) # <Color.red: 1> print(Color.red.name) # red print( Color['red'].name ) # red print( Color(1).name ) # red
リファレンス:Python 言語リファレンス
共用体型
定数
定数自体はないが、暗黙のルールとして単語を区切るアンダースコアと大文字のみで定義された変数を定数とみなす。
let
リストの初期化
[] を使用してリストオブジェクトとして宣言する。
arr = ['abc', 'def', 'ghi'] print(arr) # ['abc', 'def', 'ghi'] for value in arr: print( value ) # 'abc', 'def', 'ghi' arr = ['abc', 0] # 異なる型の要素を格納することができる print( arr ) # ['abc', 0]
リストに変換
タプルや辞書をリストに変換
# タプルをリストに変換 arr1 = ('abc', 'def', 'ghi') print(arr1) # ('abc', 'def', 'ghi') arr2 = list(arr1) print(arr2) # ['abc', 'def', 'ghi'] # 辞書をリストに変換 dic = { 'abc': 'ABC', 'def' : 'DEF', 'ghi' : 'GHI' } print(dic) # {'def': 'DEF', 'ghi': 'GHI', 'abc': 'ABC'} arr2 = list(dic) print(arr2) # ['def', 'ghi', 'abc']
連続する整数値のリストで初期化
連続する整数値のリストで初期化する
l = list(range(2, 10)) print( l ) # [2, 3, 4, 5, 6, 7, 8, 9]
要素の参照
arr = ['abc', 'def', 'ghi'] print(arr[1]) # def
リストの要素数を取得
arr = ['abc', 'def', 'ghi'] print( len( arr ) ) # 3
リストに要素を追加
指定したインデックスに要素を挿入する
arr = ['abc', 'def', 'ghi'] arr.insert( 1, 'jkl' ) print(arr) # ['abc', 'jkl', 'def', 'ghi'] arr.insert( 5, 'mno' ) print(arr) # ['abc', 'def', 'ghi', 'jkl', 'mno']
リストの最後に要素を追加する
arr = ['abc', 'def', 'ghi'] arr.append( 'jkl' ) print( arr ) # ['abc', 'def', 'ghi', 'jkl']
リストに他のリストをつないでできた新しいリストを返す。
arr1 = ['abc', 'def', 'ghi'] arr2 = ['jkl', 'mno', 'pqr'] arr3 = [1, 2, 3] arr4 = arr1 + arr2 + arr3 print( arr4 ) # ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 1, 2, 3]
リストに他のリストをつないでできた新しいリストを返す。
arr1 = ['abc', 'def', 'ghi'] arr2 = ['jkl', 'mno', 'pqr'] arr3 = [1, 2, 3] arr1.extend( arr2 ) arr1.extend( arr3 ) print( arr1 ) # ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 1, 2, 3]
リストの要素を削除
指定したインデックスの要素を取り除く
arr = ['abc', 'def', 'ghi', 'jkl', 'mno' ] del arr[1] print( arr ) # ['abc', 'ghi', 'jkl', 'mno']
インデックスで指定した範囲内の要素を取り除く。第二引数は インデックス - 1 で指定する。
arr = ['abc', 'def', 'ghi', 'jkl', 'mno' ] del arr[2:3] print( arr ) # ['abc', 'def', 'jkl', 'mno']
指定されたインデックスの要素を取り除く。インデックスを指定しない場合は最後の要素を取り除く。
戻り値は取り除いた要素。
arr = ['abc', 'def', 'ghi', 'jkl', 'mno' ] print( arr.pop( 2 ) ) # ghi print( arr ) # ['abc', 'def', 'jkl', 'mno'] print( arr.pop() ) # mno print( arr ) # ['abc', 'def', 'jkl']
指定された要素を取り除く
arr = ['abc', 'def', 'ghi', 'jkl', 'mno' ] arr.remove( 'def' ) print( arr ) # ['abc', 'ghi', 'jkl', 'mno'] arr.remove( 'xyz' ) # 実行時エラー
全ての要素を取り除く
arr = ['abc', 'def', 'ghi', 'jkl', 'mno' ] arr.clear() print( arr ) # []
スライス
リストの一部を取り出して新しいリストを返す。第二引数は インデックス - 1 で指定する。
arr = ['abc', 'def', 'ghi', 'jkl', 'mno' ] arr1 = arr[2:3] print( arr1 ) # ['ghi']
リストの検索
引数に与えられた内容と同じ内容を持つリスト要素の内、最初のものの添字を返す。
arr = ['abc', 'def', 'ghi', 'abc', 'def' ] print( arr.index( 'def' ) ) # 1 print( arr.index( 'xyz' ) ) # 実行時エラー
引数に与えられた内容と同じ内容を持つ場合 True を返す。
arr = ['abc', 'def', 'ghi', 'abc', 'def' ] print( 'def' in arr ) # True print( 'xyz' in arr ) # False
リストを逆順に変換
リストの要素を反転させる。
arr = ['abc', 'def', 'ghi', 'jkl', 'mno' ] arr.reverse() print( arr ) # ['mno', 'jkl', 'ghi', 'def', 'abc']
リストをソートする
リストの要素をソートする。
arr1 = ['mno', 'abc', 'ghi', 'jkl', 'def' ] arr2 = [ 3, 2, 14, 5, 0, 12 ] arr1.sort() print( arr1 ) # ['abc', 'def', 'ghi', 'jkl', 'mno'] arr2.sort() print( arr2 ) # [0, 2, 3, 5, 12, 14] arr2.sort( reverse = True ) print( arr2 ) # [14, 12, 5, 3, 2, 0]
条件を満たす要素数
条件を満たす要素数を取得する
arr = [ 3, 2, 14, 5, 0, 12 ] print(len([i for i in arr if i % 2 == 0])) # 4
all()、any()
all():すべての要素がTrueであればTrueを返す。
any():いずれかの要素がTrueであればTrueを返す
allTrue = [ True, 1 ] mixed = [ True, 1, False, 0 ] allFalse = [ False, 0 ] print(all(allTrue)) # True print(all(allFalse)) # False print(not all(allFalse)) # True print(all(allFalse)) # False print(any(allTrue)) # True print(any(mixed)) # True print(any(allFalse)) # True
連想配列の初期化
keyと値を使用して辞書を作成する。: の左がkey、右が値となる。
dic = { 'abc': 'ABC', 'def' : 'DEF', 'ghi' : 'GHI' } print(dic) # {'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI'}
辞書に変換
リストやタプルを辞書に変換する。キーと値のセットを並べた二重配列を使用する。
# リストを辞書に変換 arr = [ ['abc', 'ABC'], ['def', 'DEF'] ] dic = dict( arr ) print( dic ) # {'abc': 'ABC', 'def': 'DEF'} # タプルを辞書に変換 arr = ( ('abc', 'ABC'), ('def', 'DEF') ) dic = dict( arr ) print( dic ) # {'abc': 'ABC', 'def': 'DEF'}
連想配列の要素数
連想配列の要素数を取得する。
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } print( len(dic) ) # 3
キー/値の列挙
キー/値を列挙する
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } for key_value in dic.items(): print( key_value ); # ('ghi', 'GHI') # ('def', 'DEF') # ('abc', 'ABC')
キーの列挙
キーを列挙する
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } for key in dic.keys(): print( key ); # 'ghi' # 'def' # 'abc'
値の列挙
値を列挙する
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } for value in dic.values(): print( value ); # 'GHI' # 'DEF' # 'ABC'
連想配列の検索
keyの値を使用して検索する。
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } print( dic['abc'] ) # ABC print( dic['xyz'] ) # 実行時エラー
連想配列の修正
keyの値を使用して対象の要素を修正する。
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } dic['abc'] = 'xyz' print( dic ) # {'def': 'DEF', 'ghi': 'GHI', 'abc': 'xyz'}
連想配列に追加
keyと値を使用して要素を追加する。
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } dic['xyz'] = 'XYZ' print(dic) # {'abc': 'ABC', 'def': 'DEF', 'xyz': 'XYZ', 'ghi': 'GHI'}
連想配列の削除
keyの値を使用して要素を削除する。
dic = { 'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI' } del dic['def'] print( dic ) # {'abc': 'ABC', 'ghi': 'GHI'} del dic['xyz'] print(dic) # 実行時エラー
タプルの初期化
()を使用して初期化する。
Pythonにおけるタプルとは他言語と異なる意味を持つようである。Pythonでは修正不可能な配列の作成に使用するらしい。
arr = ('abc', 'def', 'ghi') print(arr) # ('abc', 'def', 'ghi') for value in arr: print( value ) # 'abc', 'def', 'ghi' arr = ('abc', 0) # 異なる型の要素を格納することができる print( arr ) # ('abc', 0)
タプルに変換
リストや辞書をタプルに変換する。辞書はキー値のみとなる。
# リストをタプルに変換 arr1 = ['abc', 'def', 'ghi'] print( arr1 ) # ['abc', 'def', 'ghi'] arr2 = tuple( arr1 ) print( arr2 ) # ('abc', 'def', 'ghi') # 辞書をタプルに変換 dic = { 'abc': 'ABC', 'def' : 'DEF', 'ghi' : 'GHI' } print(dic) # {'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI'} arr2 = tuple(dic) print(arr2) # ('abc', 'def', 'ghi')
タプルの修正
タプルは修正できない
arr = ('abc', 'def', 'ghi') arr[0] = 'xyz' # 実行時エラー
追加と削除
集合( set型 )は{}を使用して並べる。ただし辞書とは異なり単一要素を並べる。重複する要素は追加できず順番もない。
arr = { 'abc', 'def', 'ghi' } arr.add( 'jkl' ) print(list(arr)) # ['abc', 'def', 'ghi', 'jkl'] arr.add( 'jkl' ) print(list(arr)) # ['abc', 'def', 'ghi', 'jkl'] arr.remove( 'jkl' ) print(list(arr)) # ['abc', 'def', 'ghi']
差集合
差集合では、同一要素を除外して残った要素を返す
arr1 = { 'abc', 'def', 'ghi', 'mno' } arr2 = { 'abc', 'def', 'ghi', 'jkl' } print( list( arr2 - arr1 ) ) # ['jkl'] print( list( arr2.difference( arr1 ) ) ) # ['jkl']
共通集合(積集合)
共通集合では、共通の要素を返す。
arr1 = { 'abc', 'def', 'ghi' } arr2 = { 'jkl', 'ghi' } print( list( arr2 & arr1 ) ) # ['ghi'] print( list( arr2.intersection( arr1 ) ) ) # ['ghi']
対象差
どちらかにのみ含まれている要素を返す
arr1 = { 'abc', 'def', 'ghi', 'mno' } arr2 = { 'abc', 'def', 'ghi', 'jkl' } print( list( arr2 ^ arr1 ) ) # ['jkl', 'mno'] print( list( arr2.symmetric_difference( arr1 ) ) ) # ['jkl', 'mno']
和集合
和集合
arr1 = { 'abc', 'def', 'ghi' } arr2 = {'jkl'} print( list( arr2 | arr1 ) ) # ['abc', 'def', 'ghi', 'jkl'] print( list( arr2.union( arr1 ) ) ) # ['abc', 'def', 'ghi', 'jkl']
包含判定
すべての要素が含まれているかを判定する
arr1 = { 'abc', 'def', 'ghi' } arr2 = {'jkl'} print( arr2 >= arr1 ) # False print( arr2 <= arr1 ) # False arr2 = arr1.copy() print( arr2 >= arr1 ) # True print( arr2 <= arr1 ) # True arr2.add( 'jkl' ) print( arr2 >= arr1 ) # True print( arr2 <= arr1 ) # False # イコールをつけない場合は、完全一致する場合 False となる arr1 = { 'abc', 'def', 'ghi' } arr2 = {'jkl'} print( arr2 > arr1 ) # False print( arr2 < arr1 ) # False arr2 = arr1.copy() print( arr2 > arr1 ) # False print( arr2 < arr1 ) # False arr2.add( 'jkl' ) print( arr2 > arr1 ) # True print( arr2 < arr1 ) # False
共通要素を持たないかの判定
共通要素を持たない場合は True を返す
arr1 = { 'abc', 'def', 'ghi' } arr2 = {'jkl'} print( arr2.isdisjoint( arr1 ) ) # True arr2 = arr1.copy() print( arr2.isdisjoint( arr1 ) ) # False arr2.add( 'jkl' ) print( arr2.isdisjoint( arr1 ) ) # False
if 文
インデントにはタブを使用する。タブを使用することは言語仕様として決まっているので必ずいれるようにする。
num1 = 12 num2 = 34 num3 = 56 if num1 > num2: print( 'num1 > num2' ) elif num1 < num2: print( 'num1 < num2' ) else: print( 'num1 = num2' ) # 'num1 < num2' if num1 < num2 and num2 < num3: print( 'num1 < num2 and num2 < num3' ) else: print( 'else' ) # 'num1 < num2 and num2 < num3' if num1 < num2 < num3: # Python では他言語と異なり左のような記述が可能 print( 'num1 < num2 < num3' ) else: print( 'else' ) # 'num1 < num2 < num3' if num1 < num2: pass # なにもしない else: print( 'else' ) if num1 < num2: pass # コンパイルエラー
リファレンス:Python 言語リファレンス
for 文
break、および continue は他言語と同じように使用できる。
arr = ['abc', 'def', 'ghi', 'jkl', 'mno', ] for value in arr: print( value ) # 'abc' # 'def' # 'ghi' # 'jkl' # 'mno' for i in range( 0, len(arr) ): print( arr[i] ) # 'abc' # 'def' # 'ghi' # 'jkl' # 'mno'
リファレンス:Python 言語リファレンス
while 文
arr = ['abc', 'def', 'ghi', 'jkl', 'mno', ] i = 0 while i < len( arr ): print( arr[i] ) i = i + 1 # 'abc' # 'def' # 'ghi' # 'jkl' # 'mno'
リファレンス:Python 言語リファレンス
例外処理
import sys def foo(): try: num = 1 / 0 print( "try" ) except Exception as err: print( "err => " + str( err ) ) print( traceback.format_exc(sys.exc_info()[2]) ) raise err # 例外を呼び出し元に返す finally: print( "finally" ) try: foo() except Exception as err2: print( "err2 => " + str( err2 ) ) # err => division by zero # finally # err2 => division by zero
リファレンス:Python 言語リファレンス
with
with ブロックから抜けるときに対応する終了処理を実行する。例外処理で抜ける場合であっても確実に終了処理を実行できる。
with open('c:\\a.txt', 'r') as f print( f.read() ) # f.close() は不要
リファレンス:Python 言語リファレンス
関数
x = 0 y = 0 def func1( x, y ): return x + y print( func1( 1, 2 ) ) # 3
ラムダ式( 無名関数 )
コロンの右側に式を記述し、その結果を返す。
func = lambda x, y : x + y print( func( 1, 2 ) ) # 3
引数の規定値
def calc(price, count, taxRate = 0): print( 'taxRate -> ' + str( taxRate ) ) return price * count * (1.0 + taxRate / 100.0) print(calc(1200, 10)) # 12000.0 print(calc(1200, 10, 8)) # 12960.0
可変長引数
*を使用するとタプル、**を使用すると連想配列となる
def add( *args ): return ''.join(args) print(add( 'abc', 'def', 'ghi' )) # abcdefghi def swap( **args ): dic = {} for item in args.items(): dic[item[1]] = item[0] return dic print( swap( ABC = 'abc', DEF = 'def', GHI = 'ghi' ) ) # {'abc': 'ABC', 'def': 'DEF', 'ghi': 'GHI'}
関数のオーバーロード
Pythonではオーバーロードは対応していない。オーバーロードに似た実装を行う場合、引数の規定値を使用する。
def add( x, y = None ): ret = 0 if y == None: return x else: return x + y print( add( 10 ) ) # 10 print( add( 10, 20 ) ) # 30
ジェネリックス
type関数を使用して引数の型ごとに処理を分岐することでジェネリックスっぽい実装が可能
def func( data ): t = type( data ) if t == int: print( "int" ) elif t == str: print( "string" ) elif t == list: print( "list" ) else: print( "not" ) func( 1 ) # 'int' func( 'abc' ) # 'string' func( [ 0, 1, 2 ] ) # 'list'
yield
ジェネレータの一種。ここでいうジェネレータとは呼び出される度に次々と異なる値を返す関数のことを示す。
関数が呼び出されると最初の yield の結果を返し、次の呼び出しではその次の yield の結果を返す。
def generator(): yield 1 yield 2 yield 3 for line in generator(): print( line ) # 1, 2, 3
クラス
関数の第一引数の self は必須。これはクラスのインスタンス自身を示す。
class Player: _id = 0 _name = '' _life = 0 def __init__( self, id, name, life ): # コンストラクタ self._id = id self._name = name self._life = life def print( self ): return str( self._id ) + ', ' + self._name + ', ' + str( self._life ) player = Player( 0, 'test1', 100 ) print( player.print() ) # 0, 'test1', 100
リファレンス:Python 言語リファレンス
プロパティ
class PropertyClass: def __init__(self, msg): # __は外部からアクセスできない self.__message = msg # オブジェクトの文字列表現を定義するために用いる特殊メソッド def __str__(self): return self.message # getter @property def message(self): return self.__message # プロパティmessageに対応するsetter @message.setter def message(self, value): if value != '': self.__message = value pc= PropertyClass('Hello') print(pc.message) # Hello pc.message = '' # messageの中身を「Hello」から空文字列に変更 print(pc) # Hello
継承
class Human: _id = 0 _name = "" def __init__(self, id, name): self._id = id self._name = name def get(self): return str( self._id ) + ', ' + self._name class Player( Human ): _shield = 0 # コンストラクタはスーパークラスのコンストラクタをオーバーライドしている def __init__(self, id, name, shield): # スーパークラスのコンストラクタを呼び出し Human.__init__( self, id, name ) self._shield = shield def get(self): return str( self._id ) + ', ' + self._name + ', ' + str( self._shield ) human = Human( 1, 'test1' ) print( human.get() ) # '1, test1' player = Player( 1, 'test1', 100 ) print( player.get() ) # '1, test1, 100'
リファレンス:Python 言語リファレンス
インターフェース
from abc import ABCMeta, abstractmethod class Human( metaclass=ABCMeta ): @abstractmethod def move( self, x, y ): pass # pass 文は何もしない @abstractmethod def x( self ): pass @abstractmethod def y( self ): pass class Wepon( metaclass=ABCMeta ): @abstractmethod def attack( self ): pass class Player( Human, Wepon ): _x = 0; _y = 0; _wepon = ""; def __init__( self, x, y, wepon ): self._x = x self._y = y self._wepon = wepon def move( self, x, y ): # 抽象クラスで定義したメソッドを実装する必要がある。実装しない場合実行時エラー。 self._x = self._x + x self._y = self._y + y def x( self ): # 抽象クラスで定義したメソッドを実装する必要がある。実装しない場合実行時エラー。 return self._x def y( self ): # 抽象クラスで定義したメソッドを実装する必要がある。実装しない場合実行時エラー。 return self._y def attack( self ): # 抽象クラスで定義したメソッドを実装する必要がある。実装しない場合実行時エラー。 return self._wepon player = Player( 1, 2, 'handgun' ) print( str( player.x() ) + ', ' + str( player.y() ) ) # '1, 2' player.move( 3, 4 ) print( str( player.x() ) + ', ' + str( player.y() ) ) # '4, 6' print( player.attack() ) # 'hundgun' human = Human() # 実行時エラー
リファレンス:Python 言語リファレンス
C#からPython呼び出し
Visual Studio 上で NuGetパッケージ の管理で IronPython を参照追加する。
// C# ソース using System; using System.Windows.Forms; using IronPython.Hosting; using Microsoft.Scripting.Hosting; namespace WindowsFormsApplication13 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); scope.SetVariable(this.button1.Name, this.button1); ScriptSource source = engine.CreateScriptSourceFromFile(@"test.py"); source.Execute(scope); } } }
# Python ソース # coding: utf-8 # .NET Frameworkのクラスライブラリを使う宣言 import clr clr.AddReference("System.Drawing") from System.Drawing import * # デザイン変更 button1.Text = "aaa" button1.Left = 10
バッチ処理
Pythonを使用してバックアップを行います。 なおbatファイルからPythonファイルを呼び出す際、パスを短くできるようにするためにシステム環境変数の Path変数 に C:\Python34; のようにpython.exeが存在するパスを追加しておくこと。
rem python_backup.bat rem Pythonファイルを呼び出す python "D:\Sample\python\src\python_backup.py" >d:\python_backup.log
# python_backup.py import os import shutil import datetime def outputLog( msg ): print( datetime.datetime.now().strftime( "%Y/%m/%d %H:%M:%S\t" ) + msg ) # コマンドラインから実行した場合のみ処理する if __name__ == "__main__": # バックアップ元 srcPath = "C:\\Python34" now = datetime.datetime.now().strftime( "%Y%m%d" ) # バックアップ先 dstPath = "C:\\Python34_backup\\" + now try: outputLog( "開始" ) # バックアップもとのフォルダの存在確認 if os.path.exists( srcPath ): # バックアップ先が存在する場合は削除 if os.path.exists( dstPath ): outputLog( "バックアップ先フォルダの削除開始" ) shutil.rmtree( dstPath ) outputLog( "バックアップ開始" ) outputLog( srcPath + " -> " + dstPath ) # フォルダごとバックアップ shutil.copytree(srcPath, dstPath) outputLog( "バックアップ終了" ) else: outputLog( "バックアップ対象のフォルダなし" ) except Exception as err: outputLog( "err => " + str( err ) ) finally: outputLog( "終了" )
2016/03/13 21:15:39 開始 2016/03/13 21:15:39 バックアップ先フォルダの削除開始 2016/03/13 21:15:47 バックアップ開始 2016/03/13 21:15:47 C:\Python34 -> C:\Python34_backup\20160313 2016/03/13 21:17:34 バックアップ終了 2016/03/13 21:17:34 終了
リスト内包表記
既存のリストから条件分岐などを指定して新しいリストに格納する。 {}で囲むと集合または辞書内包表記となる。
# 1〜10のリストから各要素を2倍したリストを作成する result = [x*2 for x in range(1, 11)] print(result) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # 1〜10のリストから偶数のみのリストを作成する result = [x for x in range(1, 11) if x % 2 == 0] print(result) # [2, 4, 6, 8, 10] # 三項演算子の結果ごとに加工した値でリストを作成する # 次のサンプルでは偶数であるかそうでないかでリストに作成する値を変えている result = [(x, 'odd') if x % 2 else (x, 'even') for x in range(1, 11)] print(result) # [(1, 'odd'), (2, 'even'), (3, 'odd'), (4, 'even'), (5, 'odd'), (6, 'even'), (7, 'odd'), (8, 'even'), (9, 'odd'), (10, 'even')] # if句と代入式の組み合わせパターン。代入式は処理の結果を変数に代入しながら条件分岐を行えるようにするための式。 def f(x): return x + 0.5 lst = [0.06, 0.85, 0.96, 0.79, -0.73, 0.30, -0.81, -0.57, 0.56, 0.32] result = [(x, y) for x in lst if (y := f(x)) > 1.0] print(result) # [(0.85, 1.35), (0.96, 1.46), (0.79, 1.29), (0.56, 1.06)]
ジェネレーター式
()で囲むと値を一つずつ返すジェネレータを生成する。
generator = (x * 2 for x in range(5)) for num in generator: print(num)
正規表現
. 任意の一文字 ? 直前の文字がない、または1文字だけ * 直前の文字がない、または1文字以上 + 直前の文字が1文字以上
import re # rはraw文字列つまり\がエスケープ文字とならずそのまま\という文字として認識されるようになる。詳細はre --- 正規表現操作 # re.IGNORECASEを指定すると大文字区別しない pattern = re.compile(r'(P(yth|l)|Z).[pn]e?', flags=re.IGNORECASE) print(pattern.search('python')) # <re.Match object; span=(0, 6), match='python'>
pickleモジュール
python内のオブジェクトをシリアライズしてファイル出力する
import pickle from datetime import datetime d = datetime.now() with open('date.pkl', 'wb') as f: pickle.dump(d, f) with open('date.pkl', 'rb') as f: d = pickle.load(f) print(d) # 2024-03-24 08:48:09.717227
pycodestyle
PEP 8コーディング規約に違反していないかチェックする ※macosの場合 1)pip install pycodestyle 2)pycodestyle sample.py
flake8
未使用変数の宣言など論理的なチェックを行う ※macosの場合 1)pip install flake8 2)flake8 sample.py