logo

Python でリストを反復処理する方法

リストは、Python で最もよく使用されるデータ構造の 1 つです。私たちは、単純な問題から複雑な問題まで、さまざまなアプリケーションでリストを使用し続けています。 Python では、配列の代わりにリストが使用され、次のような利点があります。

  1. ダイナミックなサイズ
  2. 異なるデータ型の項目を 1 つのリストに保存できます

順序どおりにリストから簡単にデータにアクセスできます。セットとは異なり、データは順序付けされていません。データにアクセスするには、リスト内の各要素を反復処理するいくつかの方法を使用できます。このチュートリアルでは、例を示しながらすべての方法を説明します。

1. ループ

    while ループを使用する:
 list1 = [3, 5, 7, 2, 4] count = 0 while (count <len(list1)): 1 print (list1 [count]) count="count" + < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>We created a list with a few elements. Initially, count = 0. We&apos;re printing the element at the &apos;count&apos; index and incrementing the count in the while loop. When the count reaches the length of the list, the loop will be terminated, and all the elements will already be accessed.</p> <p> <strong>Mechanism:</strong> </p> <table class="table"> <tr> <td>count = 0</td> <td>list1 [0]</td> <td>3</td> </tr> <tr> <td>count = 1</td> <td>list1 [1]</td> <td>5</td> </tr> <tr> <td>count = 2</td> <td>list1 [2]</td> <td>7</td> </tr> <tr> <td>count = 3</td> <td>list1 [3]</td> <td>2</td> </tr> <tr> <td>count = 4</td> <td>list1 [4]</td> <td>4</td> </tr> <tr> <td>count = 5 = len (list1)</td> <td>-</td> <td>-</td> </tr> </table> <ul> <tr><td>Using for loop:</td>  </tr></ul> <pre> list1 = [3, 5, 7, 2, 4] for i in list1: print (i) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-2.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>Using for-in, we accessed all the i&apos;s, the elements inside the list.</p> <ul> <tr><td>Using for and range:</td>  </tr></ul> <pre> list1 = [3, 5, 7, 2, 4] length = len (list1) for i in range (0, len (list1)): print (list1 [i]) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-3.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>The range function helps the &apos;for&apos; loop to iterate from 0 to the given list&apos;s length.</p> <p> <strong>Mechanism:</strong> </p> <table class="table"> <tr> <td>the range gives - 0</td> <td>list1 [0]</td> <td>3</td> </tr> <tr> <td>the range gives - 1</td> <td>list1 [1]</td> <td>5</td> </tr> <tr> <td>the range gives - 2</td> <td>list1 [2]</td> <td>7</td> </tr> <tr> <td>the range gives - 3</td> <td>list1 [3]</td> <td>2</td> </tr> <tr> <td>the range gives - 4</td> <td>list1 [4]</td> <td>4</td> </tr> </table> <ul> <li>The range function doesn&apos;t give the last element specified - len (list1) = 5 is not given.</li> </ul> <h2>2. Using List Comprehension</h2> <p>This is the simple and suggested way to iterate through a list in Python.</p> <p> <strong>Code:</strong> </p> <pre> list1 = [3, 5, 7, 2, 4] [print (i) for i in list1] print (&apos;
&apos;) [print (list1 [i]) for i in range (0, len (list1))] print (&apos;
&apos;) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-4.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>We can use for loops inside a list comprehension. We used the same for loops we used in the above examples but inside a list in a single line. This way, we can reduce the length of the code and also list comprehension is a very subtle and efficient way to put loops in lists.</p> <h2>3. Using enumerate():</h2> <p>The enumerate function converts the given list into a list of tuples. Another important fact about this function is that it keeps count of the iterations. This is a built-in function in Python.</p> <p> <strong>Code:</strong> </p> <pre> list1 = [3, 5, 7, 2, 4] for i, j in enumerate (list1): print (&apos;index = &apos;, i, &apos;value: &apos;, j) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-5.webp" alt="How to Iterate through a List in Python"> <h2>4. Using lambda function and map():</h2> <p>These are anonymous functions. There is a function map () in Python that can accept a function as an argument, and it calls the function with every element in the iterable, and a new list with all the elements from the iterable will be returned.</p> <p> <strong>Code:</strong> </p> <pre> list1 = [3, 6, 1, 8, 7] result = list (map (lambda num: num, list1)) print (result) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-6.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>The lambda num: num is given as an input to the map function along with the list. The function will take every single element in the list, accept it, and then return it. The map () function will pass the list elements one by one to the lambda function to return the elements.</p> <h2>What if we want to Iterate Multi-dimensional Lists?</h2> <p>There is an inbuilt module in Python designed to perform operations on multi-dimensional lists.</p> <p> <strong>1. To get numpy:</strong> </p> <p>Check if Python and pip are installed by opening the cmd via search and typing the commands:</p> <p> <strong>Python -version</strong> </p> <p> <strong>Pip --version</strong> </p> <p>If both Python and PIP are present in our system, it is now time to install our library:</p> <p> <strong>2. Open cmd from the start menu</strong> </p> <p> <strong>3. Type the command</strong> </p> <h3>pip install numpy</h3> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python.webp" alt="How to Iterate through a List in Python"> <p>All the library packages, data, and sub-packages will be installed one after the other.</p> <p> <strong>Code:</strong> </p> <pre> import numpy list1 = numpy. arange (9) list1 = list1. reshape (3, 3) for x in numpy. nditer (list1): print (x) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-7.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>We imported the numpy module. Using the arrange method, we created an array with 9 elements. We accessed the list by reshaping it to 3 * 3 (rows * columns) using the reshape. Using the nditer function, we printed each element in the list.</p> <hr></len(list1)):>

出力:

Python でリストを反復処理する方法

理解:

for-in を使用して、すべての i、つまりリスト内の要素にアクセスしました。

    for と range の使用:
 list1 = [3, 5, 7, 2, 4] length = len (list1) for i in range (0, len (list1)): print (list1 [i]) 

出力:

Python でリストを反復処理する方法

理解:

range 関数は、「for」ループが 0 から指定されたリストの長さまで反復するのに役立ちます。

Javaでマップを反復する

機構:

範囲は - 0 を返します シート1 [0] 3
範囲は - 1 になります シート1 [1] 5
範囲は - 2 になります シート1 [2] 7
範囲は - 3 になります シート1 [3] 2
範囲は - 4 になります シート1 [4] 4
  • range 関数は指定された最後の要素を与えません - len (list1) = 5 が与えられません。

2. リスト内包表記の使用

これは、Python でリストを反復処理するためのシンプルで推奨される方法です。

コード:

 list1 = [3, 5, 7, 2, 4] [print (i) for i in list1] print (&apos;
&apos;) [print (list1 [i]) for i in range (0, len (list1))] print (&apos;
&apos;) 

出力:

Python でリストを反復処理する方法

理解:

PowerShell の複数行コメント

リスト内包表記内で for ループを使用できます。上記の例で使用したのと同じ for ループを 1 行のリスト内で使用しました。このようにして、コードの長さを減らすことができ、リスト内包表記はループをリストに入れるための非常に巧妙で効率的な方法です。

3. enumerate() の使用:

enumerate 関数は、指定されたリストをタプルのリストに変換します。この関数に関するもう 1 つの重要な事実は、反復のカウントを保持することです。これは Python の組み込み関数です。

コード:

 list1 = [3, 5, 7, 2, 4] for i, j in enumerate (list1): print (&apos;index = &apos;, i, &apos;value: &apos;, j) 

出力:

Python でリストを反復処理する方法

4. ラムダ関数とmap()の使用:

これらは匿名関数です。 Python には関数を引数として受け入れることができる関数マップ () があり、反復可能内のすべての要素を使用して関数を呼び出し、反復可能のすべての要素を含む新しいリストが返されます。

コード:

 list1 = [3, 6, 1, 8, 7] result = list (map (lambda num: num, list1)) print (result) 

出力:

Python でリストを反復処理する方法

理解:

ラムダ num: num は、リストとともにマップ関数への入力として与えられます。この関数は、リスト内のすべての要素を受け取り、それを返します。 map () 関数はリスト要素を 1 つずつ lambda 関数に渡して要素を返します。

多次元リストを反復したい場合はどうすればよいでしょうか?

Python には、多次元リストに対する操作を実行するように設計された組み込みモジュールがあります。

1. numpy を取得するには:

検索で cmd を開き、次のコマンドを入力して、Python と pip がインストールされているかどうかを確認します。

Python -バージョン

Pip --バージョン

Python と PIP の両方がシステムに存在する場合は、ライブラリをインストールします。

2.スタートメニューからcmdを開きます。

3. コマンドを入力します。

pip インストール numpy

Python でリストを反復処理する方法

すべてのライブラリ パッケージ、データ、サブパッケージが順番にインストールされます。

コード:

Javaのrepl
 import numpy list1 = numpy. arange (9) list1 = list1. reshape (3, 3) for x in numpy. nditer (list1): print (x) 

出力:

Python でリストを反復処理する方法

理解:

numpy モジュールをインポートしました。アレンジメソッドを使用して、9 つの要素を持つ配列を作成しました。 reshape を使用してリストを 3 * 3 (行 * 列) に再形成することで、リストにアクセスしました。 nditer 関数を使用して、リスト内の各要素を出力しました。