PythonSucks
基本的な入出力
print のクソっぷりは 3000 で解決するらしい。
print が文
>>> map(str, [1,2])
['1', '2']
>>> map(print, [1,2])
File "<stdin>", line 1
map(print, [1,2])
^
SyntaxError: invalid syntax
print とコンマ
print "abc", print "def",
は "abc def" と出力した後でインタプリタ終了時に改行が足されるって感じか。
print "abc\n", print "def\n",
は "abc\ndef\n" なのである。
raw_input("hoge") とかで出力もできる
まともな標準入出力は
import sys
sys.stdout.write("Hello, world!\n")
めんどくさいなぁ。
input
一行入力して「evalして」かえす関数
一つのことはは一つの方法で
リスト内包表記と map
>>> [x+1 for x in [1,2]] [2, 3] >>> map(lambda x: x+1, [1,2]) [2, 3]
もちろん普通にループを書いても良い
引数
>>> len("hoge")
4
>>> len("hoge",)
4
クォート
"hoge\n" と 'hoge\n' は同じ意味。
not in 演算子
>>> 2 not in [1,2] False >>> not 2 in [1,2] False
is not 演算子
>>> type("") is not str
False
>>> not type("") is str
False
>>> type("") not is str
File "<stdin>", line 1
type("") not is str
^
SyntaxError: invalid syntax
標準ライブラリ
スーパー便利関数 str#title()
>>> "abc def".title() 'Abc Def' >>> "wendy's".title() "Wendy'S"
どのモジュールに?
os.chdir, os.path.dirname, sys.stdout, __builtin__.open
悪くもないんだけど、覚えられない。
os.removedirs vs rm -rf
removedirs(name)
removedirs(path)
Super-rmdir; remove a leaf directory and all empty intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs. Errors during this latter phase are
ignored -- they generally mean that a directory was not empty.
定番
self
self 多い。
class C:
def f(self):
print 'hoge'
def g(self):
f() # NameError: global name 'f' is not defined
C().g()
個人的には下記のケースの方がエラーメッセージで混乱する。
class C:
def f():
print 'hoge'
def g(self):
self.f() # TypeError: f() takes no arguments (1 given)
C().g()
del と len
これらが obj.del や obj.len で無いという文句も定番。 del 予約語は 3000 で消えるらしい。
list comprehension と lambda
>>> fs = [ lambda: i for i in range( 8 ) ] >>> fs[0]() 7 >>> i = 3 >>> fs[0]() 3
Keyword(s):
References:[] [FrontPage]