Pythonの文法と戯れる
pythonの文法の興味深いところをメモってみました。
- リストのスライス
>>> list = [1, 2, 3, 4, 5] >>> list[1] 2 >>> list[1:] [2, 3, 4, 5] >>> list[1:3] [2, 3] >>> list[:3] [1, 2, 3] >>> list[:] [1, 2, 3, 4, 5] >>> list[-1] 5 >>> list[-2] 4 >>> list[-2:] [4, 5] >>> list[:-2] [1, 2, 3] >>> list[-2:-1] [4] >>> list[0] 1 >>> list[-0] 1 >>> list[+0] 1
- タプルの連結
>>> (1, 2, 3) + 4 ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> TypeError: can only concatenate tuple (not "int") to tuple >>> (1, 2, 3) + (4) ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> TypeError: can only concatenate tuple (not "int") to tuple >>> (1, 2, 3) + (4,) (1, 2, 3, 4)
- 範囲条件
>>> x = 3 >>> if 1 < x and x < 5: ... print 'yatta!' ... ... yatta! >>> if 1 < x < 5: ... print 'yatta!' ... ... yatta!
- リスト代入とタプル代入
>>> a, b = 1, 2 >>> print a, b 1 2 >>> [a, b] = 3, 4 >>> print a, b 3 4 >>> (a, b) = 5, 6 >>> print a, b 5 6 >>> (a, b) = (7, 8) >>> print a, b 7 8 >>> [a, b] = [9, 10] >>> print a, b 9 10 >>> (a, b) = [11, 12] >>> print a, b 11 12 >>> [a, b] = (13, 14) >>> print a, b 13 14
- キーワード引数
>>> def hoge(value, type=2, status=3): ... print value, type, status ... >>> hoge(1) 1 2 3 >>> hoge(4, 5) 4 5 3 >>> hoge(4, 5, 6) 4 5 6 >>> >>> hoge(1, status=2) 1 2 2 >>> hoge(1, status=7) 1 2 7 >>> hoge(1, type=7, status=8) 1 7 8 >>> hoge(1, status=9, type=10) 1 10 9
- 複数の引数
>>> def fuga(*args, **kwargs): ... print args, kwargs ... >>> fuga(1) (1,) {} >>> fuga(1,2) (1, 2) {} >>> fuga(1,2,value=3) (1, 2) {'value': 3} >>> fuga(1,2,value=3,type=4) (1, 2) {'type': 4, 'value': 3}
- リスト内包表記
>>> [x for x in range(1,10) if x % 2] [1, 3, 5, 7, 9] >>> [x * 2 for x in range(1,10)] [2, 4, 6, 8, 10, 12, 14, 16, 18]
- lambda式(無名関数)
>>> def func1(x): ... return x * 2 ... >>> for x in range(1,5): ... print func1(x) ... ... 2 4 6 8 10 >>> func2 = lambda x : x * 2 >>> for x in range(1,5): ... print func2(x) ... ... 2 4 6 8 10
- ジェネレータ
>>> def hoge(list): ... for i in list: ... yield i ... ... >>> fuga = hoge(range(5)) >>> fuga.next() 0 >>> fuga.next() 1 >>> fuga.next() 2 >>> fuga.next() 3 >>> fuga.next() 4 >>> fuga.next() ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> StopIteration
- デコレータ
>>> def p(*args, **kwargs): ... print args, kwargs ... >>> p(1, hoge=2) (1,) {'hoge': 2} >>> def add_line(func): ... def wrapper(*args, **kwargs): ... print '----------------' ... func(*args, **kwargs) ... print '----------------' ... wrapper.__name__ = func.__name__ ... return wrapper ... >>> @add_line ... def p(*args, **kwargs): ... print args, kwargs ... >>> p(1, hoge=2) ---------------- (1,) {'hoge': 2} ----------------