SlideShare a Scribd company logo
Pythonのデータ型を
もっと理解する
malo21st   
【オンライン】はんなりPython #31 LT会 2020/07/17
おまえだれよ
✤ ⽥中丸 祐治(たなかまる ゆうじ)
malo21st(まろツウェンティーファースト)
✤ IT業界とは関係のない完全趣味でPythonやってます。
✤ 福岡を中⼼に、Pythonコミュニティに出没しています。
✤ Github : https://github.com/malo21st
✤ Twitter : @malo21st
なぜ、malo21st なの?
malo は、⾼校の国語の先⽣が
「⽥中⿇呂」と呼んだのが始まり。
21st は、今が 21世紀 だから。
いきなりで何ですが
dir ( 'abc ') を実行したことありますか
dir ( 'abc ' ) を実行したら、こうなります。
_ _***_ _
特殊メソッド
33個
その他
⼀般メソッド
45個
dunder
double underscore
便宜的に
このLTに
限り使⽤
int・float・str の メソッド
= +
125個 68個 57個
int・float・str の 特殊メソッド(68個)
演算:
__add__ x+y x.__add__(y)
__mul__ __rmul__ x*y x.__mul__(y) y.__rmul__(x)
__mod__ __rmod__ x%y x.__mod__(y) y.__rmod__(x)
比較:__eq__ __ne__ __lt__ __le__ __gt__ __ge__
インスタンス・クラス:__init__ __new__ __class__
__init_subclass__ __hash__ __subclasshook__
文字列としての値:__repr__ __str__ __format__
pickle:__reduce__ __reduce_ex__ __getnewargs__
属性:__getattribute__ __setattr__ __delattr__ __dir__
ヘルプ:__doc__ メモリ使用量:__sizeof__
__and__ __rand__ x & y
__or__ __ror__ x | y
__xor__ __rxor__ x ^ y
__lshift__ __rlshift__ x << y
__rshift__ __rrshift__ x >> y
__invert__ ~x ~10 -> -11
__ceil__ math.ceil(x)
__floor__ math.foor(x)
__index__ itr_x[x] x.__index__()
__set_format__ '{:.5f}'.format(1.0)
__getformat__ '1.00000'
文字列は、リストのように振舞う
__len__ len(str_x)
__contains__ x in str_x
__getitem__ str_x[x]
__iter__ iter(str_x)
__abs__ abs(x) x.__abs__(x)
__pos__ __neg__ +x -x
__int__ __float__ int(x) float(x)
__round__ round(x)
__trunc__ math.trunc(x)
__bool__ bool(x)
__radd__ x + y y.__radd__(x)
__sub__ __rsub__ x - y x.__sub__(y) y.__rsub__(x)
__pow__ __rpow__ x ** y x.__pow__(y) y.__rpow__(x)
__truediv__ __rtruediv__ x / y x.__truediv__(y) y.__rtruediv__(x)
__floordiv__ __rfloordiv__ x // y x.__floordiv__(y) y.__rfloordiv__(x)
__divmod__ __rdivmod__ divmod(x, y) x.__divmod__(y) y.__rdivmod__(x)
int・float・str の 一般メソッド(57個)
文字列の置換:replace translate maketrans 含むか判定:startswith endswith  位置の判定:find rfind index rindex
構成要素の判定:isalnum isalpha isdigit islower isupper isspace istitle isdecimal isnumeric isascii
その他の判定:isprintable isidentifier 書式・整形:rjust ljust center format format_map expandtabs zfill
大文字・小文字の変換:capitalize swapcase title lower upper casefold リストに変換:split rsplit splitlines
文字の削除:strip lstrip rstrip 区切り:partition rpartition 連結・結合:join  出現回数:count 文字コード:encode
is_integer (1.0).is_integer() -> True
as_integer_ratio 少数を分数で近似する
(0.25).as_integer_ratio() -> (1, 4)
fromhex hex 16進文字列とバイト列の変換
h = ‘010203ff’
bytes.fromhex(h) -> b’x01x02x03xff'
bytes.hex(b) -> ‘010203ff'
numerator プロパティ
denominator プロパティ
from fractions import Fraction
x = Fraction(1, 3)
x.numerator -> 1
x.denominator -> 3
bit_length
(0b10).bit_length() -> 2
整数とバイト列の変換
to_bytes
from_bytes
real プロパティ
imag プロパティ
c = 3 + 4j
c.real -> 3
c.imag -> 4
conjugate
c.conjugate() -> 3 - 4j 共役複素数
list・tuple・dict・set の メソッド
= +
79個 48個 31個
list・tuple・dict・setの特殊メソッド(48個)
イテラブル:__iter__ iter(cont)    シーケンス:__len__ __contains__ len(cont) x in cont
比較:__eq__ __ne__ __lt__ __le__ __gt__ __ge__
インスタンス・クラス:__init__ __new__ __class__ __init_subclass__ __hash__ __subclasshook__
属性:__getattribute__ __setattr__ __delattr__ __dir__
文字列としての値:__repr__ __str__ __format__
メモリ使用量:__sizeof__ ヘルプ:__doc__ pickle:__reduce__ __reduce_ex__ pickle.dump(file)
__imul__ itr_x *= int
__iadd__ itr_x += itr_y
__reversed__ reversed(itr_x)
__add__ itr_x + itr_y
__mul__ itr_x * int
__rmul__ int * itr_x
__getitem__ itr_x[key]
__getnewargs__ pickle.load(file)
__setitem__ itr_x[key] = value
__delitem__ del itr_x[key]
論理演算:
__and__ __rand__ set_x & set_y
__or__ __ror__ set_x | set_y
__xor__ __rxor__ set_x ^ set_y
__sub__ __rsub__ set_x - set_y
累算代入演算:
__iand__ set_x &= set_y
__ior__ set_x |= set_y
__ixor__ set_x ^= set_y
__isub__ set_x -= set_y
list・tuple・dict・setの一般メソッド(31個)
intersection_update A.intersection_update(B,C) -> A={3}
difference_update B.difference_update(A,D) -> B={4}
symmetric_difference_update
A.symmetric_difference_update(B) -> A={1,2,4,5}
新しい集合を返す
intersection difference symmetric_difference
nion C=A.union(B) -> C={1,2,3,4,5,6}  Aはそのまま
p=[0,1,1,2,3]
remove p.remove(1) -> [0,1,2,3]
pop m.pop() -> 6 m=[0,4]
clear n.clear() -> []
copy o = l.copy() 別のインスタンス
e = {3:’d', 4:’e'}
update d.update(e) 要素を追加して更新
-> {0:’a', 1:’b', 2:’c’, 3:’d', 4:’e'}
d = {0:’a', 1:’b', 2:’c'} # key:values
get d.get(1) -> 'b'
keys d.keys() -> dict_keys([0, 1, 2])
values d.values() -> dict_values(['a','b','c'])
items d.items()
-> dict_items([(0,’a’),(1,’b’),(2,'c')])
setdefault d.setdefault(3,’d')
       -> {0:’a’,1:’b',2:’c’,3:’d’}
popitem d.popitem() ランダムに取り出す
       -> (2, ‘c’) d={0:’a',1:’b',3:'d'}
fromkeys dict.fromkeys(d,’’) キーをコピーして新辞書
       -> {0: '', 1: '', 2: ''}
l=[0,1] m=[0,4,6] n=[3,1,0,4]
append l.append(2) -> [0,1,2]
extend l.extend([2,3]) -> [0,1,2,3]
insert m.insert(1,2) -> [0,2,4,6]
reverse n.reverse() -> [4,0,1,3]
sort n.sort() -> [0,1,3,4] 昇順
count [0,1,2,3,3].count(3) -> 2
index (0,1,2,3,3).index(3) -> 3
A={1, 2, 3} B={3, 4, 5} C={1, 3} D={5, 6}
add A.add(4) -> A={1, 2, 3, 4}
discard A.discard(3) -> A={1, 2}
判定:
issubset C.issubset(A) -> True Cは、Aの部分集合
issuperset A.issuperset(C) -> True Aは、Cの上位集合
isdisjoint A.isdisjoint(D) -> True Aは、Dと素である
結 論
• Pythonのデータ型は全てオブジェクトであり、たくさんのメソッドを持つ。
• 特殊メソッドを理解することで、データ型の特徴を把握できる。
• 各データ型の⼀般メソッドを把握することで、余計なコードを書かずに済む。
思わぬ収穫
• 集合の演算ができた dict & set - list - tuple
ご清聴 ありがとうございました。
• 本⽇の資料
 https://github.com/malo21st/hannariPy200717
【オンライン】はんなりPython #31 LT会 2020/07/17

More Related Content

PPTX
Python 学習教材
PPTX
Python 学習教材 (300~309ページ)
PDF
Pythonの処理系はどのように実装され,どのように動いているのか? 我々はその実態を調査すべくアマゾンへと飛んだ.
PDF
About Pointer
PPTX
Python 学習教材 (~299ページ)
PDF
PRML読書会#2,#3資料
PDF
C++の黒魔術
PDF
Unity + C#講座①
Python 学習教材
Python 学習教材 (300~309ページ)
Pythonの処理系はどのように実装され,どのように動いているのか? 我々はその実態を調査すべくアマゾンへと飛んだ.
About Pointer
Python 学習教材 (~299ページ)
PRML読書会#2,#3資料
C++の黒魔術
Unity + C#講座①

Similar to Pythonのデータ型をもっと理解する (20)

PDF
Python勉強会3-コレクションとファイル
PPT
Pythonintro
PDF
Python勉強会2-数値と文字列
PDF
200319 eash python_shareslide
PDF
ALPSチュートリアル(4) Python入門
PDF
Pythonで始めるDropboxAPI
PDF
R language definition3.1_3.2
PDF
数式をnumpyに落としこむコツ
ODP
第2回R勉強会1
PDF
すごいHaskell読書会 第六章 発表資料
PPT
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと
KEY
Algebraic DP: 動的計画法を書きやすく
PDF
Gura プログラミング言語の紹介
PPTX
第3章 型とクラス
PPTX
第3章 型とクラス
PDF
Pythonはどうやってlen関数で長さを手にいれているの?
PDF
Programming in Scala Chapter 17 Collections
PDF
Intoroduction of Pandas with Python
PDF
すごいHaskell読書会#1 in 大阪
PDF
Adding simpl GVN path into GHC
Python勉強会3-コレクションとファイル
Pythonintro
Python勉強会2-数値と文字列
200319 eash python_shareslide
ALPSチュートリアル(4) Python入門
Pythonで始めるDropboxAPI
R language definition3.1_3.2
数式をnumpyに落としこむコツ
第2回R勉強会1
すごいHaskell読書会 第六章 発表資料
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと
Algebraic DP: 動的計画法を書きやすく
Gura プログラミング言語の紹介
第3章 型とクラス
第3章 型とクラス
Pythonはどうやってlen関数で長さを手にいれているの?
Programming in Scala Chapter 17 Collections
Intoroduction of Pandas with Python
すごいHaskell読書会#1 in 大阪
Adding simpl GVN path into GHC
Ad

Pythonのデータ型をもっと理解する

  • 2. おまえだれよ ✤ ⽥中丸 祐治(たなかまる ゆうじ) malo21st(まろツウェンティーファースト) ✤ IT業界とは関係のない完全趣味でPythonやってます。 ✤ 福岡を中⼼に、Pythonコミュニティに出没しています。 ✤ Github : https://github.com/malo21st ✤ Twitter : @malo21st なぜ、malo21st なの? malo は、⾼校の国語の先⽣が 「⽥中⿇呂」と呼んだのが始まり。 21st は、今が 21世紀 だから。
  • 3. いきなりで何ですが dir ( 'abc ') を実行したことありますか
  • 4. dir ( 'abc ' ) を実行したら、こうなります。 _ _***_ _ 特殊メソッド 33個 その他 ⼀般メソッド 45個 dunder double underscore 便宜的に このLTに 限り使⽤
  • 6. int・float・str の 特殊メソッド(68個) 演算: __add__ x+y x.__add__(y) __mul__ __rmul__ x*y x.__mul__(y) y.__rmul__(x) __mod__ __rmod__ x%y x.__mod__(y) y.__rmod__(x) 比較:__eq__ __ne__ __lt__ __le__ __gt__ __ge__ インスタンス・クラス:__init__ __new__ __class__ __init_subclass__ __hash__ __subclasshook__ 文字列としての値:__repr__ __str__ __format__ pickle:__reduce__ __reduce_ex__ __getnewargs__ 属性:__getattribute__ __setattr__ __delattr__ __dir__ ヘルプ:__doc__ メモリ使用量:__sizeof__ __and__ __rand__ x & y __or__ __ror__ x | y __xor__ __rxor__ x ^ y __lshift__ __rlshift__ x << y __rshift__ __rrshift__ x >> y __invert__ ~x ~10 -> -11 __ceil__ math.ceil(x) __floor__ math.foor(x) __index__ itr_x[x] x.__index__() __set_format__ '{:.5f}'.format(1.0) __getformat__ '1.00000' 文字列は、リストのように振舞う __len__ len(str_x) __contains__ x in str_x __getitem__ str_x[x] __iter__ iter(str_x) __abs__ abs(x) x.__abs__(x) __pos__ __neg__ +x -x __int__ __float__ int(x) float(x) __round__ round(x) __trunc__ math.trunc(x) __bool__ bool(x) __radd__ x + y y.__radd__(x) __sub__ __rsub__ x - y x.__sub__(y) y.__rsub__(x) __pow__ __rpow__ x ** y x.__pow__(y) y.__rpow__(x) __truediv__ __rtruediv__ x / y x.__truediv__(y) y.__rtruediv__(x) __floordiv__ __rfloordiv__ x // y x.__floordiv__(y) y.__rfloordiv__(x) __divmod__ __rdivmod__ divmod(x, y) x.__divmod__(y) y.__rdivmod__(x)
  • 7. int・float・str の 一般メソッド(57個) 文字列の置換:replace translate maketrans 含むか判定:startswith endswith  位置の判定:find rfind index rindex 構成要素の判定:isalnum isalpha isdigit islower isupper isspace istitle isdecimal isnumeric isascii その他の判定:isprintable isidentifier 書式・整形:rjust ljust center format format_map expandtabs zfill 大文字・小文字の変換:capitalize swapcase title lower upper casefold リストに変換:split rsplit splitlines 文字の削除:strip lstrip rstrip 区切り:partition rpartition 連結・結合:join  出現回数:count 文字コード:encode is_integer (1.0).is_integer() -> True as_integer_ratio 少数を分数で近似する (0.25).as_integer_ratio() -> (1, 4) fromhex hex 16進文字列とバイト列の変換 h = ‘010203ff’ bytes.fromhex(h) -> b’x01x02x03xff' bytes.hex(b) -> ‘010203ff' numerator プロパティ denominator プロパティ from fractions import Fraction x = Fraction(1, 3) x.numerator -> 1 x.denominator -> 3 bit_length (0b10).bit_length() -> 2 整数とバイト列の変換 to_bytes from_bytes real プロパティ imag プロパティ c = 3 + 4j c.real -> 3 c.imag -> 4 conjugate c.conjugate() -> 3 - 4j 共役複素数
  • 9. list・tuple・dict・setの特殊メソッド(48個) イテラブル:__iter__ iter(cont)    シーケンス:__len__ __contains__ len(cont) x in cont 比較:__eq__ __ne__ __lt__ __le__ __gt__ __ge__ インスタンス・クラス:__init__ __new__ __class__ __init_subclass__ __hash__ __subclasshook__ 属性:__getattribute__ __setattr__ __delattr__ __dir__ 文字列としての値:__repr__ __str__ __format__ メモリ使用量:__sizeof__ ヘルプ:__doc__ pickle:__reduce__ __reduce_ex__ pickle.dump(file) __imul__ itr_x *= int __iadd__ itr_x += itr_y __reversed__ reversed(itr_x) __add__ itr_x + itr_y __mul__ itr_x * int __rmul__ int * itr_x __getitem__ itr_x[key] __getnewargs__ pickle.load(file) __setitem__ itr_x[key] = value __delitem__ del itr_x[key] 論理演算: __and__ __rand__ set_x & set_y __or__ __ror__ set_x | set_y __xor__ __rxor__ set_x ^ set_y __sub__ __rsub__ set_x - set_y 累算代入演算: __iand__ set_x &= set_y __ior__ set_x |= set_y __ixor__ set_x ^= set_y __isub__ set_x -= set_y
  • 10. list・tuple・dict・setの一般メソッド(31個) intersection_update A.intersection_update(B,C) -> A={3} difference_update B.difference_update(A,D) -> B={4} symmetric_difference_update A.symmetric_difference_update(B) -> A={1,2,4,5} 新しい集合を返す intersection difference symmetric_difference nion C=A.union(B) -> C={1,2,3,4,5,6}  Aはそのまま p=[0,1,1,2,3] remove p.remove(1) -> [0,1,2,3] pop m.pop() -> 6 m=[0,4] clear n.clear() -> [] copy o = l.copy() 別のインスタンス e = {3:’d', 4:’e'} update d.update(e) 要素を追加して更新 -> {0:’a', 1:’b', 2:’c’, 3:’d', 4:’e'} d = {0:’a', 1:’b', 2:’c'} # key:values get d.get(1) -> 'b' keys d.keys() -> dict_keys([0, 1, 2]) values d.values() -> dict_values(['a','b','c']) items d.items() -> dict_items([(0,’a’),(1,’b’),(2,'c')]) setdefault d.setdefault(3,’d')        -> {0:’a’,1:’b',2:’c’,3:’d’} popitem d.popitem() ランダムに取り出す        -> (2, ‘c’) d={0:’a',1:’b',3:'d'} fromkeys dict.fromkeys(d,’’) キーをコピーして新辞書        -> {0: '', 1: '', 2: ''} l=[0,1] m=[0,4,6] n=[3,1,0,4] append l.append(2) -> [0,1,2] extend l.extend([2,3]) -> [0,1,2,3] insert m.insert(1,2) -> [0,2,4,6] reverse n.reverse() -> [4,0,1,3] sort n.sort() -> [0,1,3,4] 昇順 count [0,1,2,3,3].count(3) -> 2 index (0,1,2,3,3).index(3) -> 3 A={1, 2, 3} B={3, 4, 5} C={1, 3} D={5, 6} add A.add(4) -> A={1, 2, 3, 4} discard A.discard(3) -> A={1, 2} 判定: issubset C.issubset(A) -> True Cは、Aの部分集合 issuperset A.issuperset(C) -> True Aは、Cの上位集合 isdisjoint A.isdisjoint(D) -> True Aは、Dと素である
  • 11. 結 論 • Pythonのデータ型は全てオブジェクトであり、たくさんのメソッドを持つ。 • 特殊メソッドを理解することで、データ型の特徴を把握できる。 • 各データ型の⼀般メソッドを把握することで、余計なコードを書かずに済む。 思わぬ収穫 • 集合の演算ができた dict & set - list - tuple