Pythonのリスト・タプル・集合・辞書を使ってみる

Pythonのデータ型の中で、値を複数持つことのできるリスト・タプル・辞書・集合について調べてみます。
Pythonのバージョンは3.7.0を使用しています。

リスト型

リストの使い方は全体を大括弧[] で囲って、値をカンマで区切ります。
値の取得はインデックス番号を指定する形で、末尾から数える場合はマイナスの値になります。

list = ['A', 'B', 'C', 'D', 'E']
print(list) # ['A', 'B', 'C', 'D', 'E']
print(list[0]) # 'A'
print(list[-1]) # 'E'

文字列を分割して配列を作成することもできます。

url = 'https://cly7796.net/blog/'
list = url.split('/')
print(list) # ['http:', '', 'cly7796.net', 'wp', '']
string.split(sep) 文字列stringをsepの値で区切ってリストにする。

スライス

次のようにコロンを使ってリストのスライスもできます。

list = ['A', 'B', 'C', 'D', 'E']
print(list[2:]) # ['C', 'D', 'E']
print(list[:2]) # ['A', 'B']
print(list[1:3]) # ['B', 'C']
print(list[:]) # ['A', 'B', 'C', 'D', 'E']
print(list[::2]) # ['A', 'C', 'E']

list[2:]の場合はインデックスの2番目から最後まで、list[:2]の場合は最初から2番目まで、list[1:3]の場合はインデックスの1番目から3番目まで、list[:]の場合はすべてをスライスします。
後ろにさらにコロンを付けることで、いくつおきにスライスするかも指定できます。

list[start:end(:step)] start位置からend位置までの値を取得。
省略した場合はstartが0でendが要素数(最後まで取得)になる。
stepが設定されている場合はその値分ステップしながら取得。

演算

リスト同士の連結や乗算もできます。

list = ['A', 'B', 'C']
list2 = [1, 2, 3]
print(list + list2) # ['A', 'B', 'C', 1, 2, 3]
print(list * 2) # ['A', 'B', 'C', 'A', 'B', 'C']

追加・変更・削除

要素の追加や変更、削除をやってみます。

list = ['A', 'B', 'C']

# 変更
list[0] = 1
print(list) # [1, 'B', 'C']

# 追加
list.append(4)
print(list) # [1, 'B', 'C', 4]
list[1:3] = [2, 3]
print(list) # [1, 2, 3, 4]
list.extend([5, 6])
print(list) # [1, 2, 3, 4, 5, 6]
list.insert(0, -1)
print(list) # [-1, 1, 2, 3, 4, 5, 6]

# 削除
list.remove(6)
print(list) # [-1, 1, 2, 3, 4, 5]
pop = list.pop(4)
print(pop) # 4
print(list) # [-1, 1, 2, 3, 5]
del list[0]
print(list) # [1, 2, 3, 5]
del list[1:3]
print(list) # [1, 5]
list.clear()
print(list) # []
list.append(x) リストの最後にxを追加。
list.extend(iterable) リストの最後にiterableを追加。
list.insert(index, x) indexの位置にxを追加。
list.remove(x) リスト内の最初のxの要素を削除。
リストにxの要素がない場合はエラー。
del list[index] リストからindexの位置の要素を削除。
スライスの形で指定することも可能。
list.pop(index) リストからindexの位置の要素を削除して、削除した要素を返す。
indexが指定されていない場合は最後の要素を削除して返す。
list.clear() リストからすべての要素を削除。

要素数の取得や検索

list = ['red', 'green', 'blue', 'red', 'blue']
print(len(list)) # 5
print(list.index('red')) # 0
print(list.count('red')) # 2
print('red' in list) # True
print('red' not in list) # False
len(list) リストの要素数を取得。
list.index(x) リスト内の最初のxのインデックスを返す。
リスト内にxがない場合はエラー。
list.count(x) リスト内にあるxの数を返す。
x in list xがリスト内にあるかどうかを調べる。
ある場合はTrue、ない場合はFalseを返す。
x not in list xがリスト内にないかどうかを調べる。
ない場合はTrue、ある場合はFalseを返す。

最小値・最大値・合計値を取得

list = [1, 2, 3]
print(min(list)) # 1
print(max(list)) # 3
print(sum(list)) # 6
min.(list) リスト内の最小値を取得。
max.(list) リスト内の最大値を取得。
sum.(list) リスト内の合計値を取得。

並び順の変更

list = ['banana', 'apple', 'peach', 'orange']
list.sort()
print(list) # ['apple', 'banana', 'orange', 'peach']
list.reverse()
print(list) # ['peach', 'orange', 'banana', 'apple']
list.sort(key=None, reverse=False) リストの要素をソートする。
list.reverse() リストの要素を逆順にする。

コピー

リストのコピーは通常参照渡しになります。

list = ['A', 'B', 'C']
list2 = list
list2[0] = 0
print(list) # [0, 'B', 'C']
print(list2) # [0, 'B', 'C']

copy()を使ってコピーすることで値渡しにできます。

list = ['A', 'B', 'C']
list2 = list.copy()
list2[0] = 0
print(list) # ['A', 'B', 'C']
print(list2) # [0, 'B', 'C']
list.copy(list) リストのコピーを返す。

もしくはスライスで以下のようにすることでも可能です。

list = ['A', 'B', 'C']
list2 = list[:]
list2[0] = 0
print(list) # ['A', 'B', 'C']
print(list2) # [0, 'B', 'C']

 

タプル型

タプルはリストとほぼ同じですが、値の変更ができない点が異なります。
タプルの使い方は全体を丸括弧() で囲って、値をカンマで区切ります。

tuple = (1, 2, 3, 4, 5)
print(tuple) # (1, 2, 3, 4, 5)
print(tuple[0]) # 1
print(tuple[-1]) # 5
 
# スライス
print(tuple[2:]) # (3, 4, 5)
print(tuple[::2]) # (1, 3, 5)
 
# 演算
tuple2 = ('A', 'B', 'C')
print(tuple + tuple2) # (1, 2, 3, 4, 5, 'A', 'B', 'C')
print(tuple2 * 2) # ('A', 'B', 'C', 'A', 'B', 'C')
 
# 要素数の取得・検索
print(len(tuple)) # 5
print(tuple.index(1)) # 0
print(tuple.count(1)) # 1
print(1 in tuple) # True
print(1 not in tuple) # False

# 最小値・最大値・合計
print(min(tuple)) # 1
print(max(tuple)) # 5
print(sum(tuple)) # 15

リストの項目で試したように、値や要素数の取得や演算、検索などを行うことができます。

ただし値の変更ができないので、以下のような追加や変更、削除、並び替えなどは行えません。

tuple = ('A', 'B', 'C', 'D', 'E')

# 追加・変更・削除
tuple[0] = 0 # TypeError: 'tuple' object does not support item assignment
tuple.append(6) # AttributeError: 'tuple' object has no attribute 'append'
tuple.extend([7, 8, 9]) # AttributeError: 'tuple' object has no attribute 'extend'
tuple.insert(0, -1) # AttributeError: 'tuple' object has no attribute 'insert'
tuple.remove('D') # AttributeError: 'tuple' object has no attribute 'remove'
pop = tuple.pop(4) # AttributeError: 'tuple' object has no attribute 'pop'
del tuple[0] # TypeError: 'tuple' object doesn't support item deletion
tuple.clear() # AttributeError: 'tuple' object has no attribute 'clear'

# 並び替え
tuple.sort() # AttributeError: 'tuple' object has no attribute 'sort'
tuple.reverse() # AttributeError: 'tuple' object has no attribute 'reverse'

※実際にはエラーが出た時点で処理が止まるので、上記のようにエラーが連続して出ることはありません。

値の変更はできませんが、再代入をすることはできます。

tuple = ('A', 'B', 'C')
print(tuple) # ('A', 'B', 'C')
print(id(tuple)) # 1729535287016

# 再代入
tuple = (1, 2, 3)
print(tuple) # (1, 2, 3)
print(id(tuple)) # 1729535287232

ただし、再代入した際はオブジェクトのIDは変更されます。

id(object) objectのIDを調べる。

リスト型をタプル型に、タプル型をリスト型に変換することもできます。

l = [1, 2, 3]
t = ('A', 'B', 'C')
print(tuple(l)) # (1, 2, 3)
print(list(t)) # ['A', 'B', 'C']
tuple(list) listをタプル型に変換する。
list(tuple) tupleをリスト型に変換する。

 

集合型

集合は要素の重複が不可なデータ型です。
前述のリスト型やタプル型と違い、各要素は順序付けられていません。
全体を中括弧{} で囲って、値をカンマで区切ります。

set = {'banana', 'banana', 'apple', 'peach', 'apple', 'orange', 'peach'}
print(set) # {'banana', 'apple', 'peach', 'orange'}
print(set[0]) # TypeError: 'set' object does not support indexing

同じ要素が複数ある場合は1つにまとめられ、インデックス番号で要素を取得することができません。

リストから集合を作成することもできます。

list = ['banana', 'banana', 'apple', 'peach', 'apple', 'orange', 'peach']
print(set(list)) # {'banana', 'peach', 'orange', 'apple'}

要素の追加や削除、変更は以下のようにします。

set = {'red', 'red', 'green', 'blue'}
print(set) # {'red', 'blue', 'green'}

set.add('yellow')
print(set) # {'yellow', 'red', 'blue', 'green'}
set.remove('blue')
print(set) # {'yellow', 'red', 'green'}
set.clear()
print(set) # set()
set.add(x) 集合にxを追加。
set.remove(x) 集合からxを削除。
set.clear() 集合からすべての要素を削除。

要素数の取得や検索

set = {'red', 'red', 'green', 'blue'}
print(set) # {'blue', 'red', 'green'}
print(len(set)) # 3
print('red' in set) # True
print('red' not in set) # False

リストでも試したlen()とin、not inが使えます。
index()とcount()は集合では使えません。

演算

set1 = {'red', 'green'}
set2 = {'red', 'black'}

print(set1 - set2) # {'green'}
print(set1 | set2) # {'red', 'green', 'black'}
print(set1 & set2) # {'red'}
print(set1 ^ set2) # {'green', 'black'}
set1 – set2 set1に含まれset2に含まれない要素で集合を作成。
set1 | set2 set1とset2の要素で集合を作成。
set1 & set2 set1とset2に共通する要素で集合を作成。
set1 ^ set2 set1とset2のどちらかにだけ含まれる要素で集合を作成。

 

辞書型

辞書はキーと値のペアで管理するデータ型です。
集合型と同じく、各要素は順序付けられていません。
全体を波括弧{} で囲って、キーと値を キー: 値 のようにして、各ペアをカンマで区切ります。

dictionary = {'name': 'suzuki', 'age': 18}
print(dictionary) # {'name': 'suzuki', 'age': 18}
print(dictionary[0]) # TypeError: 'set' object does not support indexing

インデックス番号で要素を取得しようとするとエラーになります。

値を取得や変更する場合、インデックス番号ではなくキーを指定します。

dictionary = {'name': 'suzuki', 'age': 18}

# 取得
print(dictionary['name']) # suzuki

# 変更
dictionary['age'] = 22
print(dictionary) # {'name': 'suzuki', 'age': 22}

# 追加
dictionary['gender'] = 'man'
print(dictionary) # {'name': 'suzuki', 'age': 22, 'gender': 'man'}

# 削除
del dictionary['age']
print(dictionary) # {'name': 'suzuki', 'gender': 'man'}

# 存在しないキーを削除しようとするとエラー
del dictionary['address']
print(dictionary) # KeyError: 'address'

要素数の取得や検索

dictionary = {'name': 'suzuki', 'age': 18}
print(len(dictionary)) # 2
print('name' in dictionary) # True
print('name' not in dictionary) # False

キーや値を全て取得

dictionary = {'name': 'suzuki', 'age': 18}
print(list(dictionary.keys())) # ['name', 'age']
print(list(dictionary.values())) # ['suzuki', 18]
print(list(dictionary.items())) # [('name', 'suzuki'), ('age', 18)]
dictionary.keys() dictionaryのキーをすべて取得。
dictionary.values() dictionaryの値をすべて取得。
dictionary.items() dictionaryのキーと値のペアをすべて取得。

 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930