python復習まとめ1
pythonについて忘れてきたので復習。
やらなくなるとすぐ忘れてしまう……。
四則演算+α
>>> a = b = 2 #同時に代入可能。 >>> x , y = 2 , 3 #別の値も同時に代入可能。 >>> a+b 4 >>> 8/5 #切り捨てない。 1.6 >>> 7//3 #切り捨てるには//を使う。 2 >>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5
文字列
>>> str = 'abc' >>> str[1] 'b' >>> str[1:3] #2文字目から3文字目。 'bc' >>> str[-1] #最後の文字。 'c' >>> str[:2] #2文字目まで 'ab' >>> str[2:] #2文字目より後の文字。 'c' >>> str[-2:] #最後の2文字目より後の文字。 'bc' >>> 'xyz' + str 'xyzabc >>> len(str) 3
まとめると、以下の関係が成り立つ。 +---+---+---+ | a | b | c | +---+---+---+ 0 1 2 3 -3 -2 -1
リスト
リストは、角括弧の中にカンマ区切りの値を入力することで定義できる。リストのアイテムがすべて同じ型である必要はない。
>>> a = ['apple', 'orange', 13, 34.5] >>> a[1:-1] ['orange', 13] >>> 2*a ['apple', 'orange', 13, 34.5, 'apple', 'orange', 13, 34.5] >>> a[:2] + ['grape'] ['apple', 'orange', 'grape'] >>> a[2] += 2 >>> a ['apple', 'orange', 15, 34.5] >>> a[0:2] = [2,4] >>> a [2, 4, 15, 34.5] >>> a[0:2] = [] >>> a [15, 34.5] >>> a[1:1] = ['yes', 'no'] >>> a [15, 'yes', 'no', 34.5] >>> a[1] = ['great','good'] >>> a [15, ['great', 'good'], 'no', 34.5] >>> a[1] ['great', 'good'] >>> a[1][0] 'great' >>> a[1].append('nice') >>> a [15, ['great', 'good', 'nice'], 'no', 34.5] >>> len(a) 4 >>> a[:] = [] >>> a []