リストの連結は、複数の小さなリストをデイジーチェーン接続することで1つのリストを作成する行為です。
Pythonでリストを連結する方法はたくさんあります。
具体的には、プラス演算子、アンパック演算子、乗算演算子、ループ連結のためのマニュアル、 itertools.chain()
関数、組み込みのリストメソッド extend()
を使って Python で二つのリストを連結する方法について説明します。
以下のすべてのコードスニペットで、以下のリストを利用することにします。
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
プラス演算子リスト連結
Pythonで2つのリストを連結する最も簡単でわかりやすい方法は、プラス(+
)演算子です。
list_c = list_a + list_b
print (list_c)
[1, 2, 3, 4, 5, 6, 7, 8]
パック解除演算子 リスト連結
このメソッドを使うと、複数のリストを結合することができます。
これはかなり新しい機能で、Python 3.6+ からしか使えません。
unpacking 演算子はその名の通り、 iterable
オブジェクトをその要素にアンパック(展開)します。
アンパッキングは、1つのリストからたくさんの引数を生成したいときに便利です。
def foo(a, b, c, d):
return a + b + c + d
# We want to use the arguments of the following list with the foo function.
# However, foo doesn't take a list, it takes 4 numbers, which is why we need to
# unpack the list.
foo(*list_a)
# This is the same as if we were to call foo(1,2,3,4)
10
簡単に言うと、リストコンストラクタ ([a,b...
) を使って、複数のリストを次々にアンパックして新しいリストの要素を順番に生成していくのです。
list_c = [*list_a, *list_b, *list_a]
# This is the same as:
# list_c = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4]
print (list_c)
[1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4]
Multiply Operator List Concatenation (乗算演算子リスト連結)
T
for loop リスト連結
このメソッドでは、1つのリストに対してその要素を1つずつ別のリストに追加していきます。
ループが終了すると、必要な要素をすべて含む 1 つのリストができあがります。
print(list_a * 2)
[1, 2, 3, 4, 1, 2, 3, 4]
itertools.chain() リスト連結
このメソッドは iterable
で動作します。
イテレータを構築して返します。
このイテレータは、後で連鎖したリストを構築するために使用できます (結果のリストの要素の順序を記憶する矢印のようなものだと考えてください)。
for i in list_b:
list_a.append(i)
print (list_a)
内部では、以下のようなことが行われています。
[1, 2, 3, 4, 5, 6, 7, 8]
このメソッドでは、 itertools
をインポートする必要があります。
# If we were to call itertools.chain() like so
iterator = itertools.chain([1, 2], [3, 4])
# Basically the iterator is an arrow which can give us the next() element in a sequence, so if we call a list() constructor with said iterable, it works like this:
list(iterator)
# Iterator: The next element in this list is 1
[1, 2], [3, 4]
^
# Iterator: The next element in this list is 2
[1, 2], [3, 4]
^
# Iterator: The next element in this list is 3
[1, 2], [3, 4]
^
# Iterator: The next element in this list is 4
[1, 2], [3, 4]
^
# So the list() call looks something like:
list([1,2,3,4])
# Keep in mind this is all pseudocode, Python doesn't give the developer direct control over the iterator
extend() リスト連結
これはリストを展開するために使用できる組み込み関数です。
ここでは、2番目のリストの要素を追加することによって、最初のリストを拡張しています。
import itertools
list_c = list(itertools.chain(list_a, list_b))
print (list_c)
[1, 2, 3, 4, 5, 6, 7, 8]
結論
この記事では、Pythonで2つのリストを連結する5つの方法を紹介しました。
プラス演算子、アンパック演算子、マルチプル演算子、forループ、 itertools.chain()
、extend()
を使用した方法です。