PerlやRubyを使ったことあるけど、Pythonは初めてな私の個人用メモ。 http://www.python.jp/doc/nightly/tut/tut.html などから。 {{outline}} !!!データ型 !!None Pythonのヌル値は「None」。 Javaのnull、Rubyのnil、Perlのundefとの違いは後で調べる(ぉ) !!複素数 「J」または「j」で表現する。 >>> 1J**2 (-1+0j) >>> 1J**1J (0.20787957635076193+0j) >>> (1+2J).real 1.0 >>> (1+2J).imag 2.0 !!文字列 シングルクォートとダブルクォートの区別はない。 >>> print "hoge\npiyo" hoge piyo >>> print 'hoge\npiyo' # この場合もエスケープシーケンスは認識される hoge piyo エスケープシーケンスを無視して文字列リテラルを表記する際は、「r」(raw string)を指定する。 >>> print r"hoge\npiyo" hoge\npiyo 文字列には8ビット文字列とUnicode文字列が存在する。 >>> a = "hoge" >>> b = u"hoge" >>> a==b True >>> a = "日本語でおk" >>> b = u"日本語でおk" >>> a==b __main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal False !!ヒアドキュメント 「"""」で始まり、「"""」だけの行で終わる。「{{tag "'''"}}」〜「{{tag "'''"}}」も利用可能。 >>> print """ ... hoge ... piyo ... """ hoge piyo このときもraw string指定が出来る。 >>> print """ ... hogepiyo ... hoge\npiyo ... """ hogepiyo hoge piyo >>> print r""" ... hogepiyo ... hoge\npiyo ... """ hogepiyo hoge\npiyo !!リスト(配列)リテラル RubyのArrayや、Perlの無名配列とだいたい同じ? 例{{fn 麻雀やってらっしゃる方なら分かるかと思いますw}}: [1,1,1,2,3,4,5,6,7,8,9,9,9] 丸括弧で囲うと「タプル」となり、各要素が指す先の内容を入れ替えることが不可能になる。 >>> x = [1,2,3] >>> x[2] 3 >>> x[2] = 5 >>> x [1, 2, 5] >>> x = (1,2,3) >>> x[2] 3 >>> x[2] = 5 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment !!リスト・文字列等の添字 「3:6」は「3番目から、6番目'''の手前'''まで」。Rubyでいう「3...6」に相当する(「3..6」ではない)。 >>> [1,1,1,2,3,4,5,6,7,8,9,9,9][3:6] [2, 3, 4] >>> "1112345678999"[3:6] '234' 添え字は「a:b:c」のように3要素の指定もでき、「間隔cで取る」という意味になる。 >>> [1,1,1,2,3,4,5,6,7,8,9,9,9][3:10:2] # 3・5・7・9番目の要素を取得 [2, 4, 6, 8] >>> [1,1,1,2,3,4,5,6,7,8,9,9,9][6:3:-1] # 6番目から、3番目'''の次'''までの要素を逆順で取得 [5, 4, 3] 添え字の第1要素・第2要素は省略でき、省略すると端まで取る。 >>> [1,1,1,2,3,4,5,6,7,8,9,9,9][:6] [1, 1, 1, 2, 3, 4] >>> [1,1,1,2,3,4,5,6,7,8,9,9,9][6:] [5, 6, 7, 8, 9, 9, 9] >>> [1,1,1,2,3,4,5,6,7,8,9,9,9][6::-1] [5, 4, 3, 2, 1, 1, 1] !!文字列やリストの連結など 連結は「+」で行う。 >>> ["hoge", "piyo"]+["hoge", "kugyu.info"] ['hoge', 'piyo', 'hoge', 'kugyu.info'] >>> a=["hoge", "piyo"] >>> a ['hoge', 'piyo'] >>> a+=[1] >>> a ['hoge', 'piyo', 1] 1要素の連結はappendでも行える。 >>> a=[1,1,1,2,3,4,5,6,7,8,9,9,9] >>> a [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9] >>> a.append(9) >>> a [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9] 繰り返しは、(リスト)*(数)のほかに(数)*(リスト)とも書ける。 >>> ["hoge", "piyo"]*3 ['hoge', 'piyo', 'hoge', 'piyo', 'hoge', 'piyo'] >>> 3*["hoge", "piyo"] ['hoge', 'piyo', 'hoge', 'piyo', 'hoge', 'piyo'] !!辞書(連想配列) リテラルの書き方はJavaScriptと同じ? >>> x = {"hoge": 100, "piyo": 200} >>> x["hoge"] 100 >>> x["piyo"] 200 >>> x[""] Traceback (most recent call last): File "", line 1, in KeyError: '' !!関数リテラル >>> kugyu = lambda x: "Kugy" + ("u"*x) + "!" >>> kugyu(5) 'Kugyuuuuu!' >>> kugyu(10) 'Kugyuuuuuuuuuu!' !!ブール値 参考 *http://www.python.jp/doc/release/ref/Booleans.html *http://www.python.jp/doc/release/ref/customization.html ({{tag "__nonzero__"}} について) *http://www.python.jp/doc/release/ref/sequence-types.html ({{tag "__len__"}} について) 条件として利用したとき、偽と判断されるものは以下の通り。 *False *None *0(0.0なども含む) *空のコンテナ(注:文字列やリストなど) *オブジェクトについては、 **{{tag "__nonzero__"}} メソッドが定義されていれば、その返り値が0かFalseである場合 **{{tag "__nonzero__"}} メソッドが定義されておらず、{{tag "__len__"}} メソッドが定義されていれば、その返り値が0である場合 **※どちらも定義されていない場合、そのオブジェクトは真とみなされる。 !!!制御構造 !!for文 「for i in (リストとか):」で記述。 「1から5まで」などのような場合はこんな定跡がある。 >>> for i in range(1,6): ... print i ... 1 2 3 4 5 range(1,6)も「1番目から、6番目'''の手前'''まで」である。 BASICの「For i = 1 To 6 Step 2」みたいなことも出来る。 >>> for i in range(1,6,2): ... print i ... 1 3 5 文字列はタプルの一種なので、ループさせる値に指定できる。 >>> for i in "hoge": ... print i ... h o g e !!関数定義 >>> def fac(x): ... if x <= 1: ... return 1 ... else: ... return x * fac(x-1) ... >>> fac(5) 120 返り値はreturnで指定(PerlやRubyのような省略は不可)。 関数は変数と同じシンボル空間に格納される。'''関数を定義したあとに同名の変数を使うと、関数定義は消える。''' >>> def hoge(): ... print "hoge" ... >>> hoge >>> hoge() hoge >>> hoge=3 # ここで関数hogeは利用出来なくなる >>> hoge() Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not callable !!キーワード引数 >>> def hoge(a, b=2, c="sample string"): ... print a*b ... print c ... >>> hoge() Traceback (most recent call last): File "", line 1, in TypeError: hoge() takes at least 1 argument (0 given) >>> hoge(4) 8 sample string >>> hoge(4, 4, "test") 16 test >>> hoge(4, c="test", b=4) # キーワード指定 16 test !!配列を引数として展開 Rubyと同様 >>> x = [3,6] >>> range(*x) # range(3,6) とみなされる [3, 4, 5] !!辞書(連想配列)を引数として展開 Pythonではキーワード引数が使えるため、配列だけでなく辞書も引数として展開できる。 >>> def hoge(a, b=2, c="sample string"): ... print a*b ... print c ... >>> x = {"b": 7, "c": "test"} >>> hoge(3, **x) # hoge(3, b=7, c="test") とみなされる 21 test !!ループの後ろにelse for i in some_list: # do something if(some_condition): break else: # breakされなかった場合に行われる処理 !!!脚注 {{footnote_list}}