wiki:Python

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