ラベル 組み込み関数 の投稿を表示しています。 すべての投稿を表示
ラベル 組み込み関数 の投稿を表示しています。 すべての投稿を表示

2010年1月10日日曜日

オブジェクトを比較し -1, 0, 1 を返す

組み込み関数の cmp を使う

# -*- 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

詳細はドキュメントで

2009年10月29日木曜日

オブジェクトのブール値を取得する

組み込み関数 bool で取得する
# -*- 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())

詳細はドキュメントで

2009年10月16日金曜日

オブジェクトが呼び出し可能オブジェクトか調べる

呼び出し可能オブジェクトとは
int() のように末尾に括弧をつけることのできるオブジェクトのこと
関数やメソッドなどは呼び出し可能オブジェクトである

# -*- coding: utf-8 -*-

# 呼び出し可能オブジェクトか調べる
b = callable(int)

# クラスに特殊メソッド __call__ を定義すると
# 呼び出し可能オブジェクトを模倣できる
class A:
    def __call__(self, a, b):
        return a + b

a = A()

i = a(1, 2)

詳細はドキュメントで

2009年10月11日日曜日

セット

# -*- 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

詳細はドキュメントで

2009年10月10日土曜日

リスト

# -*- 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

bisectモジュールを使うと順序を保ったまま
リストに要素を追加できる
# -*- 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]

詳細はドキュメントで

2009年10月9日金曜日

オブジェクトから属性を取得する

属性とはドットで参照できるオブジェクトのこよ
例えば "abc".split() なら split が属性になる

# -*- 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)

詳細はドキュメントで

2009年10月6日火曜日

オブジェクトの文字列表現を取得する

# -*- 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

reprと``は同じ

詳細はドキュメントで

2009年10月5日月曜日

組み込み関数、例外、定数のリストを取得する

__builtin__モジュールに定義されています

import __builtin__

print dir(__builtin__)

実行すると
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

詳細はドキュメントで

2009年9月27日日曜日

インスタンスの比較

# -*- 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")

詳細はドキュメントで

文字列を計算する

i = eval("1 + 2")

詳細はドキュメントで

文字コードを文字に変換する

# -*- coding: utf-8 -*-

c = chr(97)

# Unicodeの場合
uc = unichr(97)

# 文字を文字コードに変換する
i = ord('a')

詳細はドキュメントで

整数を16進数、8進数、2進数に変換する

# -*- 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)

詳細はドキュメントで