Version 8 (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