pythonの変数

対話モード(python shell)で入力。
シャープ[#]以下はコメントなので、入力しなくてもよい。

▼変数(数字)

>>> a = 1		#aという変数に1を格納している
>>> A = 10	#大文字と小文字は違う変数として扱われる
>>> print a
1
>>> print a, A	
1 10
>>> b = -1
>>> c = 1.0001
>>> print a, A, b, c
1 10 -1 1.0001
>>> print a + A + b +c
11.0001
    
参考:3.1.1 数 http://www.python.jp/doc/release/tut/node5.html#SECTION005110000000000000000 ▼変数(文字)
>>> ========================= RESTART =========================
>>> a = "test"
>>> b = "テスト"
>>> c = "1234"
>>> d = "5678"
>>> print a, b, c
test テスト 1234
>>> print a + b + c + b
testテスト12345678
>>> print a[0]
t
>>> print a[1]
e
>>> print a[2]
s
>>> print a[3]
t
>>> print a[0], a[1], a[2], a[3]
t e s t
>>> print a[0] + a[1] + a[2] + a[3]
test
>>> print b[0]
>>> print b[0] + b[1] テ >>> print b[0] + b[1] + b[2] + b[3] + b[4] + b[5] テスト
参考:3.1.2 文字列 http://www.python.jp/doc/release/tut/node5.html#SECTION005120000000000000000 ▼数と文字は足せない
>>> ========================= RESTART =========================
>>> print 1234 + "56789"

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    print 1234 + "56789"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> a = 1234
>>> b = "5678"
>>> print a + b

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    print a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
    
▼文字と数字、変換
>>> ========================= RESTART =========================
>>> a = 1234
>>> b = "5678"
>>> print a + int(b)	#変数bを数字に変換
6912
>>> print str(a) + b	#変数aを文字に変換
12345678
>>> print `a` + b		#`a`はstr(a)と同じ
12345678
>>> 
▼リスト(配列)
>>> ========================= RESTART =========================
>>> a = [1, 2, 3, 4]
>>> b = ["test", "テスト"]
>>> c = ["1234", "5678"]
>>> print a
[1, 2, 3, 4]
>>> print a[0]	#リストの添え字(要素番号)は0(0番目)から始まる
1
>>> print b[0]
test
>>> print c[0]
1234
>>> print a[-1]	#[-1]はリストに格納された一番最後の値を指す
4
>>> print b[-1]
テスト
>>> print c[-1]
5678
>>> print a[1:3]	#[1:3]はリストの1番目から2番目まで(3番以下)を指す
[2, 3]
>>> print a + b
[1, 2, 3, 4, 'test', 'テスト']
>>> print a + b + c
[1, 2, 3, 4, 'test', 'テスト', '1234', '5678']
>>> print a[1:3] + b
[2, 3, 'test', 'テスト']
>>> print a * 2
[1, 2, 3, 4, 1, 2, 3, 4]
>>> print b * 3
['test', 'テスト', 'test', 'テスト', 'test', 'テスト']
    
▼リストのメソッド
>>> ========================= RESTART =========================
>>> a = [1, 2, 3, "test", "test"]
>>> a.append(100)
>>> print a
[1, 2, 3, 'test', 'test', 100]
>>> dir(a)		#メソッドの表示
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> a.count(100)		#()内の値がリストの中に幾つあるかカウントする
1
>>> a.count("test")
2
>>> a.index(2)		#()内の値がリストの何番目にあるか調べる
1
>>> a.index("test")	#同じ値が複数ある場合、一番最初の値が格納されている番号を返す
3
>>> a.insert(1, 1000)	#(x, y)リストのx番目にyの値を挿入する
>>> print a
[1, 1000, 2, 3, 'test', 'test', 100]
>>> b = a.pop(1)		#(x)リストのx番目値を削除しその値を戻り値として返す
>>> print b
1000
>>> print a
[1, 2, 3, 'test', 'test', 100]
>>> a.remove("test")		#()内の値をリストから削除する
>>> print a
[1, 2, 3, 'test', 100]
>>> a.reverse()			#リストの中身を逆順にする
>>> print a
[100, 'test', 3, 2, 1]
>>> a.sort()			#リストの中身をソートする
>>> print a
[1, 2, 3, 100, 'test']
    
参考: 3.1.4 リスト http://www.python.jp/doc/release/tut/node5.html#SECTION005140000000000000000 5.1 リスト型についてもう少し http://www.python.jp/doc/release/tut/node7.html#SECTION007100000000000000000 ▼辞書(連想配列)
>>> ========================= RESTART =========================
>>> a = {"blue":"青", "red":"赤", "black":"黒"}	#{キー:値}となる
>>> a["blue"]	#キーで値を指す
'青'
>>> a["red"]
'赤'
>>> b = {1:"test", "2":"テスト"}
>>> b[1]
'test'
>>> b["2"]
'テスト'
    
▼辞書のメソッド
>>> ========================= RESTART =========================
>>> a = {"red":"赤", "blue":"青", "black":"黒", "white":"白"}
>>> dir(a)		#メソッドの表示
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> a.has_key("red")	#(x)辞書の中にxのキーがあればTrueを返す
True
>>> a.has_key("gleen")	#ない時はFalseを返す
False
>>> a.has_key("赤")	#値は駄目、あくまでもキーを探す
False
>>> b = a.keys()			#変数aに格納されている全てキーをリストで返す
>>> print b
['blue', 'white', 'black', 'red']
>>> c = a.values()			#変数aに格納されている全ての値をリストで返す
>>> print c
['青', '白', '黒', '赤']
>>> d = a.items()			#変数aに格納されている全てのキーと値のペア(タプル)をリストで返す
>>> print d
[('blue', '青'), ('white', '白'), ('black', '黒'), ('red', '赤')]
>>> a.get("blue")			#(x)のキーが変数aの中にあれば、その値を返す
'青'
>>> a.get("gleen")			#見付からないときはなにも返さない
>>> a.get("gleen", "def")		#(x, y)xが見付からないとき返す値yを指定できる
'def'
>>> e = a.copy()			#変数aの中身をeにコピーする
>>> print e
{'blue': '青', 'black': '黒', 'white': '白', 'red': '赤'}
>>> f = {"gleen":"緑"}
>>> a.update(f)				#変数aに変数f(辞書)をマージする。
>>> print a
{'blue': '青', 'white': '白', 'black': '黒', 'gleen': '緑', 'red': '赤'}
>>> a.clear()				#辞書の中身をすべて削除
>>> print a
{}
    
参考:5.4 辞書 http://www.python.jp/doc/release/tut/node7.html#SECTION007400000000000000000 ▼タプル(変更不可のリスト)
>>> ========================= RESTART =========================
>>> a = [1, 2, 3, "test"]	#これはリスト
>>> b = (1, 2, 3, "test")	#これがタプル
>>> a[0] = "テスト"
>>> print a
['テスト', 2, 3, 'test']
>>> b[0] = "テスト"	#タプルの値はいじれない

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    b[0] = "テスト"
TypeError: object doesn't support item assignment
>>> print a + b		#リストとタプルは違う型なので足せない

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    print a + b
TypeError: can only concatenate list (not "tuple") to list
    
参考:5.3 タプルと配列 http://www.python.jp/doc/release/tut/node7.html#SECTION007300000000000000000 ▼タプルを辞書のキーとして使う
>>> ========================= RESTART =========================
>>> a = {[1,2]:"test", [2,3]:"テスト"}	#リストは辞書のキーとしては使えない

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    a = {[1,2]:"test", [2,3]:"テスト"}
TypeError: list objects are unhashable
>>> a = {(1, 2):"test", (2,3):"テスト"}	#タプルは辞書のキーとして使える
>>> print a[(1, 2)]
test
>>> x = 2
>>> y = 3
>>> print a[(x, y)]
テスト
    
入れ子
>>> ========================= RESTART =========================
>>> a, b, c = 1 , "123", [456, 789, 10]
>>> print a, b, c
1 123 [456, 789, 10]
>>> print c
[456, 789, 10]
>>> c[1] = ("test", "てすと")
>>> print c
[456, ('test', 'てすと'), 10]
>>> c.append(10)
>>> print c
[456, ('test', 'てすと'), 10, 10]
>>> c[-1] = ["list", "リスト", 111]
>>> print c
[456, ('test', 'てすと'), 10, ['list', 'リスト', 111]]
>>> c.append({"key":"鍵", "word":"言葉"})
>>> print c
[456, ('test', 'てすと'), 10, ['list', 'リスト', 111], {'word': '言葉', 'key': '鍵'}]
>>> c = a, b, c
>>> print c
(1, '123', [456, ('test', 'てすと'), 10, ['list', 'リスト', 111], {'word': '言葉', 'key': '鍵'}])