Python で 2つ以上のリストを連結する方法
-
Python で 2つのリストを連結する
+ -
Python で 2つのリストを連結するための
+= -
itertools.chainメソッドは Python の 2つのリストを連結する -
Python でリストを連結するための
extend()メソッド -
Python リスト連結の
[*a、*b]展開メソッド - まとめ
Python のリストは、要素の順序付きコレクションを保持するデータ構造です。
2つのリストを結合する操作は、連結と呼ばれます。Python では、in-place または out-of-place の 2つのリストを連結できます。
連結する 2つのリストがあるとします。
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
それらを連結するために複数のメソッドを使用することもできますが、長さが長くなるか、連結リストの数が増えると、パフォーマンスが異なります。
これらのさまざまな方法を紹介し、パフォーマンスを比較します。
Python で 2つのリストを連結する +
+ 演算子は 2つのリストを連結して新しいリストを返すことができます。
>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> result = list1 + list2
>>> result
[1, 2, 3, 4, 5, 6, 7, 8]
Python で 2つのリストを連結するための +=
+= は上記のメソッドと似ていますが、最初のリストのデータを変更します。
>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1 += list2
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
itertools.chain メソッドは Python の 2つのリストを連結する
itertools モジュールの chain 連続したシーケンスを 1つの単一シーケンスとして扱う、
>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> import itertools
>>> result = list(itertools.chain(list1, list2))
[1, 2, 3, 4, 5, 6, 7, 8]
itertools.chain には代替コンストラクターintertools.chain.from_iterable() があります。入力が遅延評価される単一の反復可能な引数があります。Python でリストを連結するための extend() メソッド
リストの extend メソッドは、イテラブルの要素を追加することでリストを拡張します。
>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
また、新しいリストを返すのではなく、既存のリストのデータをその場で変更します。
Python リスト連結の [*a、*b] 展開メソッド
PEP-0448 で説明されているように、反復可能なアンパック演算子の*やディクショナリのアンパック演算子の**などの追加のアンパックは、Python 3.5 から拡張されています。
>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> result = [*list1, list2]
>>> result
[1, 2, 3, 4, 5, 6, 7, 8]
この方法は、各リストを手動で解凍する場合を除き、N 個のリストの場合には適用できません。
>>> A = [1,2,3]
>>> B = [4,5,6]
>>> C = [7,8,9]
>>> [*t for t in [A,B,C]]
SyntaxError: iterable unpacking cannot be used in comprehension
まとめ
| バージョン | 所定の位置に? | |
|---|---|---|
a + b |
- | 番号 |
list(intertools.chain(a,b)) |
> = 2.3 | 番号 |
[*a, *b] |
> = 3.5 | 番号 |
a += b |
- | はい |
a.extend(b) |
- | はい |
上記のメソッドのパフォーマンスを比較するに perfplot モジュールを使用します。
グラフに示されているように、a.extend(b) と a + b メソッドはパフォーマンスがほぼ同じで、すべてのメソッドの中で最高です。list(chain(a,b)) メソッドのパフォーマンスは最悪です。
Aditya Raj is a highly skilled technical professional with a background in IT and business, holding an Integrated B.Tech (IT) and MBA (IT) from the Indian Institute of Information Technology Allahabad. With a solid foundation in data analytics, programming languages (C, Java, Python), and software environments, Aditya has excelled in various roles. He has significant experience as a Technical Content Writer for Python on multiple platforms and has interned in data analytics at Apollo Clinics. His projects demonstrate a keen interest in cutting-edge technology and problem-solving, showcasing his proficiency in areas like data mining and software development. Aditya's achievements include securing a top position in a project demonstration competition and gaining certifications in Python, SQL, and digital marketing fundamentals.
GitHub