wiki:Python

Version 9 (modified by atzm, 18 years ago) (diff)

--

Python

メモ.主に日記からの転載.

可変長引数

>>> def hoge(*a):
...     print a
>>> hoge(1, 2, 3)
(1, 2, 3)

>>> def hage(a, b, c):
...     print a, b, c
>>> a = (1, 2, 3)
>>> hage(*a)
1 2 3

>>> def hige(**a):
...     print a
>>> hige(a=1, b=2, c=3)
{'a': 1, 'c': 3, 'b': 2}

>>> def huge(a, b, c):
...     print a, b, c
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> huge(**a)
1 2 3

行列の行と列を入れ替えるワンライナー

$ cat hoge.txt 
1 2 3 4
5 6 7 8
9 10 11 12

$ python -c 'import sys; print "\n".join([" ".join(i) for i in zip(*[i.split() for i in sys.stdin])])' < hoge.txt
1 5 9
2 6 10
3 7 11
4 8 12
  • キモは zip(*list)

staticmethod

>>> class Hoge:
...     def hoge(*args):
...         print ', '.join([str(i) for i in args])
...     hoge = staticmethod(hoge)
...
>>> Hoge.hoge(1, '2', 3.3, None, False, Hoge)
1, 2, 3.3, None, False, __main__.Hoge

raw_input 中に SIGALRM 出すと EOFError

import signal
signal.signal(signal.SIGALRM, lambda *a: None)
signal.alarm(5)
raw_input()
  • 5 秒待つと EOFError.
  • 何とか回避できんもんかなぁ.

HostIP を使う

import urllib
import mimetools

class HostIP(dict):
    _URL_BASE = 'http://api.hostip.info/rough.php?position=true&ip=%s'
    _GOOGLEMAPS_BASE = 'http://maps.google.com/?q=%sN+%sE(%s)'

    def __init__(self, ipaddr):
        url = self._URL_BASE % ipaddr

        fp = urllib.urlopen(url)
        headers = mimetools.Message(fp, 0)
        fp.close()

        dict.__init__(self, headers.dict)
        self['ipaddr'] = ipaddr
        self['url'] = url
        self['googlemaps'] = self._GOOGLEMAPS_BASE % (self['latitude'], self['longitude'], ipaddr)
  • dict として使える HostIP オブジェクト.
>>> test = HostIP('210.156.41.55')
>>> for k, v in test.items():
...     print '%s: %s' % (k, v)
... 
city: Morioka
guessed: true
url: http://api.hostip.info/rough.php?position=true&ip=210.156.41.55
googlemaps: http://maps.google.com/?q=39.7N+141.15E(210.156.41.55)
latitude: 39.7
country: JAPAN
ipaddr: 210.156.41.55
country code: JP
longitude: 141.15

dict 同士のマージ

  • dict.update() だと同じキーを持つ値が上書きされてしまうので,上書きせずに足し合わせたりできる関数が欲しかった.
  • ただし,第一引数について破壊的,末端の value が数値以外に色々混ざってる時にどうなるかは知らん,という欠点あり.
def merge(my_dict, new_dict, mergetype='add'):
    for k, v in new_dict.iteritems():
        try:
            if isinstance(v, dict):
                merge(my_dict[k], v, mergetype)
            else:
                my_dict[k] = getattr(my_dict[k], '__%s__' % mergetype)(v)
        except KeyError:
            my_dict[k] = v
    return my_dict