# -*- coding: utf-8 -*- # 戻り値は数値 # x < y なら -1, x == y なら 0, x > y なら 1 i = cmp("a", "b") # クラスに特殊メソッド __cmp__ を定義すると # 結果を変更できる class A: def __cmp__(self, x): return 1
詳細はドキュメントで
# -*- coding: utf-8 -*- # 戻り値は数値 # x < y なら -1, x == y なら 0, x > y なら 1 i = cmp("a", "b") # クラスに特殊メソッド __cmp__ を定義すると # 結果を変更できる class A: def __cmp__(self, x): return 1
# -*- coding: utf-8 -*- # 組み込み関数boolで取得できる b = bool([]) # クラスに特殊メソッド __nonzero__ __len__ # を定義すると返す値を変更できる # 二つとも定義すると __nonzero__ が優先される class A: def __nonzero__(self): return False class B: def __len__(self): return 0 b = bool(A()) b = bool(B())
# -*- coding: utf-8 -*- # 呼び出し可能オブジェクトか調べる b = callable(int) # クラスに特殊メソッド __call__ を定義すると # 呼び出し可能オブジェクトを模倣できる class A: def __call__(self, a, b): return a + b a = A() i = a(1, 2)
# -*- coding: utf-8 -*- # セットを生成する st = set() st = set([1,2,3,3]) # セットに追加する st.add(4) # セットの要素を削除する st.remove(2) # セットを結合する st = st.union([4,5,6]) # セットの長さを取得する length = len(st) # セット内に要素が存在するか調べる b = 1 in st # セットをfor文で処理する for v in st: print v # セット型を継承する class A(set): pass
# -*- coding: utf-8 -*- # マップを生成する dic = {} dic = {"a": 1, "b": 2, "c": 3} dic = dict() dic = dict({"a": 1, "b": 2, "c": 3}) dic = dict(a=1, b=2, c=3) # 要素を追加する dic["d"] = 4 # 値を取得する obj = dic["d"] obj = dic.get("e", "hello") # "d"が無い場合"hello"を返す # popで取得する obj = dic.pop("d") # キーの値を更新する dic["c"] = 30 dic.update(c=40, a=10) # 要素を削除する del dic["a"] # 要素を全て削除する dic.clear() # キーのリストを取得する ls = dic.keys() # 値のリストを取得する ls = dic.values() # (キー,値)のタプルのリストを取得する ls = dic.items() # 長さを取得する length = len(dic) # キーが存在するか調べる b = "d" in dic dic.has_key("d") # for文で処理する for key in dic: print key for value in dic.itervalues(): print value for key, value in dic.iteritems(): print key, value # マップ型を継承する class A(dict): pass
# -*- coding: utf-8 -*- # 生成する ls = [] ls = [0] * 3 ls = [1, "abc", [1,2,3]] # シーケンスから生成する ls = list() ls = list("hello") # ['h', 'e', 'l', 'l', 'o'] となる # 数値のリストを生成する ls = range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] となる ls = xrange(10) # ジェネレータから生成する ls = [i for i in range(10) if i % 2 == 0] # 複数のイテレータ型から生成する ls = zip(range(3), range(3, 6)) # [(0, 3), (1, 4), (2, 5)] となる # 要素を追加する ls.append(12) # 指定した位置に要素を挿入する ls.insert(0, "ab") # 要素を入れ替える ls[2] = "456" # 要素を範囲で入れ替える ls[3:5] = [7, 8, 9] # 要素を取得する obj = ls[0] # スライスする ls = ls[0:10] # popで要素を取得する obj = ls.pop(3) # 最大の要素を取得する obj = max(ls) # 最小の要素を取得する obj = max(ls) # 要素を削除する del ls[1] # 要素を範囲で削除する del ls[2:7] # 引数と同じ要素を削除する ls.remove("ab") # 要素を全てクリアする del ls[:] # 結合する ls = ls + [45, 76, 0] + ls + ["hello", "world"] # 指定した回数リストを結合する ls = ls * 3 # ls = ls + ls + ls と同じ # 拡張する ls.extend(["er", "yu", "", "bn"]) # 長さを取得する i = len(ls) # 引数の位置を取得する i = ls.index("hello") # 引数が存在する数を取得する i = ls.count("hello") # 要素が存在するか調べる b = 1 in ls b = 1 not in ls # フィルタする def ls_filter(obj): if obj: return obj ls = filter(ls_filter, ls) # ソートする ls.sort() # 並びを反転させる ls.reverse() # for文で処理する for v in ls: print v # リスト型を継承する class A(list): pass
# -*- coding: utf-8 -*- import bisect import random ls = [] # ランダムに数値を追加する for i in random.sample(range(100), 10): bisect.insort_left(ls, i) print ls # 実行するとキレイに並んだリストが表示される # [15, 17, 24, 29, 36, 57, 68, 73, 79, 84]
# -*- coding: utf-8 -*- import inspect attr = getattr(inspect, "isclass") # inspect.isclass(inspect) と同じ b = attr(inspect) # 属性を持っているか調べる b = hasattr(inspect, "ismodule") # 属性のリストを取得する ls = dir(inspect) # メンバリストを取得する ls = inspect.getmembers(inspect)
# -*- coding: utf-8 -*- obj = 0.1 print str(obj) print unicode(obj) print repr(obj) print `obj` # クラスに特殊メソッド __str__ __unicode__ __repr__ を定義すると # str() unicode() repr() の引数として渡すことが出来る class A: def __str__(self): return "abc" def __unicode__(self): return u"abc" def __repr__(self): return "def" a = A() print str(a)
0.1 0.1 0.10000000000000001 0.10000000000000001 abc
import __builtin__ print dir(__builtin__)
# -*- coding: utf-8 -*- b = isinstance("a", basestring) # サブクラスである場合Trueを返す b = issubclass("a", basestring) # basestringはstrおよびunicodeのスーパクラス
# -*- coding: utf-8 -*- # 文字列を数値に変換する i = int("123") f = float("1.23") l = long("123l") c = complex("123") # 数値を文字列に変換する s = str(123) us = unicode(123) # クラスに特殊メソッド __int__ __long__ __float__ __complex__ を定義すると # int() long() float() complex() の引数として渡すことが出来る class A: def __int__(self): return 10 def __long__(self): return 100l def __float__(self): return 1.2 def __complex__(self): return complex(10, 23) a = A() print int(a)
# -*- coding: utf-8 -*- i = hash("abc") # 特殊メソッド__hash__を定義すればハッシュ値を変更できる class A: def __hash__(self): return 12 a = A() print hash(a)
# -*- coding: utf-8 -*- exec 'print "hello"' #ファイルの場合は execfile("filename")
# -*- coding: utf-8 -*- c = chr(97) # Unicodeの場合 uc = unichr(97) # 文字を文字コードに変換する i = ord('a')
# -*- coding: utf-8 -*- # 数値をX進数に変換する s = format(123, 'b') s = oct(123) s = hex(123) # 文字列の2進数、8進数、16進数を整数に変換する i = int("0101", 2) i = int("01234567", 8) i = int("0x0123456789abcdef", 16) # クラスに特殊メソッド __oct__ __hex__ __format__ を定義すると # oct() hex() format() の引数として渡すことが出来る class A: def __oct__(self): return "01234567" def __hex__(self): return "0x0123456789abcdef" def __format__(self, f): return "format " + f a = A() print hex(a)
OSはUbuntu 9.04
PythonはPython 2.6.2