python入門 - python3系からのまとめ

Python3系からはじめるPythonist

Pythonのリスト(配列)の検索、ソート、逆順、コピー

はじめに

Pythonのリスト(配列)の検索、ソート、コピーのまとめです。Pythonのリストは他プログラミング言語の配列と同様に扱えます。

目次

 

リストに指定した値が存在するかどうか - in

リストにその値が存在するかどうかは、inを使用します。存在していればTrueを、存在していなければFalseとなります。

list = ['a', 'b', 'c']

print('a' in list) # True
print('d' in list) # False

 

リストで指定した値の検索 - index

リストで指定した値の検索、そのインデックスを取得したい場合はindexメソッドを使用します。リスト内での、その値がもつ最初の要素のインデックスを返します。

list = ['a', 'b', 'c']
index = list.index('c')

print(index) # 2

list = ['a', 'b', 'c', 'b']
index = list.index('b')

print(index) # 1

もし、該当する項目が存在しない場合、エラーが返されます。

list = ['a', 'b', 'c']
index = list.index('d')

# エラー内容
Traceback (most recent call last):
  File "p.py", line 2, in <module>
    index = list.index('d')
ValueError: 'd' is not in list

 

リストのshallowコピー(浅いコピー) - copy, コロン:(スライス)

リストのshallowコピー(浅いコピー)にはcopyメソッドを使用します。あくまでshallowコピーであり、deepコピーではない点に注意が必要です。その例は、この項の最後に記してあります。

list = ['a', 'b', 'c']
list_copy = list.copy()

print(list_copy) # ['a', 'b', 'c']

同様に、コロン:(スライス)を使用した場合も、shallowコピーとなります。

list = ['a', 'b', 'c']
list_copy = list[:]

print(list_copy) # ['a', 'b', 'c']

shallowコピーとは、浅いコピーです。要素にリストやディクショナリなどをもつ場合、そのアドレスがコピーされるため、同一のものとなります。その点には注意が必要です。

# 想定した挙動
list = ['a', 'b', 'c']
list_copy = list.copy()

list_copy[1] = 'B'

print(list) # ['a', 'b', 'c']
print(list_copy) # ['a', 'B', 'c']

# 想定外の挙動(deepコピーではありません)
list = [[1, 2], [3, 4]]
list_copy = list.copy()

list_copy[0][0] = 9

print(list) # [[9, 2], [3, 4]]
print(list_copy) # [[9, 2], [3, 4]]

 

リストの要素のソート - sort, sorted

リストを昇順でソートします。リストの組み込みメソッドsortを使用する場合と、組み込み関数のsortedを使用する場合の二種類あります。

# sortメソッド
list = [3, 1, 2]
list.sort()

print(list) # [1, 2, 3]


# sorted関数
list = [3, 1, 2]
list = sorted(list)

print(list) # [1, 2, 3]

リストを降順でソートします。こちらも、リストの組み込みメソッドsortを使用する場合と、組み込み関数のsortedを使用する場合の二種類あります。

# sortメソッド
list = [3, 1, 2]
list.sort(reverse=True)

print(list) # [3, 2, 1]


# sorted関数
list = [3, 1, 2]
list = sorted(list, reverse=True)

print(list) # [3, 2, 1]

sortメソッドとsorted関数の違いは、任意のイテラブルを扱えるかどうかになります。下記の例のように、sorted関数の場合は、ディクショナリのキーのソートも可能となります。

dict = {3: 'c', 1: 'a', 2: 'b'}
list = sorted(dict)

print(list) # [1, 2, 3]

 

リストの要素の逆順 - reverse

リストの要素を逆順にします。

list = [3, 1, 2]
list.reverse()

print(list) # [2, 1, 3]

 

リストでの値が含まれている数 - count

リストでの値がいくつ含まれているか、そのカウント(出現回数)を返します。

list = ['a', 'b', 'c', 'b']

count_1 = list.count('a')
count_2 = list.count('b')

print(count_1) # 1
print(count_2) # 2