コレクション型
リスト(list)、タプル(tuple)、ディクショナリー(dict)などのオブジェクトを使とデータの”まとまり”を作ることができる。
- リスト (list)
いわゆる配列のこと - タプル (tuple)
中身を変更できないタイプのリスト - ディクショナリー (dict)
連想配列。Key-Value型のデータベース
list: リスト
他の言語でいう配列とほぼ同義。
1 2 3 4 | >>> [1,2,3] [1, 2, 3] >>> type([1,2,3]) <type 'list'> |
要素を削除
リスト内の要素はインデックス指定もしくは、値指定で行う。
インデックス指定で除去
del文で削除する。
1 2 3 4 | >>> list = [1,2,3] >>> del(list[1]) >>> list [1, 3] |
値指定で削除
存在しない値を指定すると例外が発生する。
1 2 3 4 5 6 7 8 | >>> list = [1,3,5] >>> list.remove(3) >>> list [1, 5] >>> list.remove(6) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list |
要素の追加と削除
appendで末尾に追加、popで末尾の要素を取り出す。
1 2 3 4 5 6 7 8 9 10 11 | >>> list [1, 3, 5] >>> list.append(7) >>> list [1, 3, 5, 7] >>> list [1, 3, 5, 7] >>> list.pop() 7 >>> list [1, 3, 5] |
ループ
forループ
1 2 3 4 5 6 7 8 | >>> list [1, 3, 5] >>> for i in list: ... print i ... 1 3 5 |
複合的な構造
リストの要素にリスト、タプル、ディクショナリーなどを含むこともできる。
1 2 3 4 5 6 7 8 9 10 11 12 | >>> list = [1,2,3] >>> list[0] 1 >>> list = [1,2,[1,2]] >>> list[1] 2 >>> list[2] [1, 2] >>> list[2][0] 1 >>> list[2][1] 2 |
tuple: タプル
リストと同じデータ構造だが、値を変更できない。listに対して使える操作のうち、値の変更を伴わないものはtupleに対しても使用できる。
1 2 3 4 | >>> (1,2,3) (1, 2, 3) >>> type((1,2,3)) <type 'tuple'> |
ループ
1 2 3 4 5 6 | >>> for i in (1,2,3): ... print i ... 1 2 3 |
dict: ディクショナリー
連想配列のようなもの。
1 2 3 4 | >>> {1:"one", 2:"two", 3:"three"} {1: 'one', 2: 'two', 3: 'three'} >>> type({1:"one", 2:"two", 3:"three"}) <type 'dict'> |
値の追加と除去
1 2 3 4 5 6 7 | >>> dict1 = {1:"one", 2:"two", 3:"three"} >>> dict1[4] = "four" >>> dict1 {1: 'one', 2: 'two', 3: 'three', 4: 'four'} >>> del(dict1[2]) >>> dict1 {1: 'one', 3: 'three', 4: 'four'} |
ループ
1 2 3 4 5 6 7 8 9 10 11 12 | >>> for i in dict1: ... i ... 1 3 4 >>> for i in dict1: ... dict1[i] ... 'one' 'three' 'four' |