logo

Python에서 목록을 반복하는 방법

리스트는 Python에서 가장 많이 사용되는 데이터 구조 중 하나입니다. 우리는 단순한 문제 해결부터 복잡한 문제까지 다양한 응용 프로그램에서 목록을 계속 사용하고 있습니다. Python에서 목록은 다음과 같은 이점으로 배열을 대체합니다.

  1. 동적 크기
  2. 단일 목록에 다양한 데이터 유형의 항목을 저장할 수 있습니다.

우리는 순서대로 목록에서 간단히 데이터에 접근할 수 있습니다. 세트와 달리 데이터는 순서가 지정되지 않습니다. 데이터에 액세스하기 위해 목록 내의 각 요소를 반복하는 여러 가지 방법을 사용할 수 있습니다. 이 튜토리얼에서는 예제를 통해 모든 방법을 다룹니다.

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에 액세스했습니다.

    대상 및 범위 사용:
 list1 = [3, 5, 7, 2, 4] length = len (list1) for i in range (0, len (list1)): print (list1 [i]) 

산출:

Python에서 목록을 반복하는 방법

이해:

range 함수는 'for' 루프가 0부터 주어진 목록의 길이까지 반복하도록 도와줍니다.

자바 문자열 인덱스

기구:

범위는 - 0을 제공합니다 시트1 [0]
범위는 - 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 루프를 사용했지만 한 줄의 목록 내부에 사용했습니다. 이런 식으로 코드 길이를 줄일 수 있으며 목록 이해는 목록에 루프를 넣는 매우 미묘하고 효율적인 방법입니다.

3. 열거() 사용:

열거 함수는 주어진 목록을 튜플 목록으로 변환합니다. 이 함수에 대한 또 다른 중요한 사실은 반복 횟수를 유지한다는 것입니다. 이것은 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에는 함수를 인수로 받아들일 수 있는 함수 map()이 있으며, 이터러블의 모든 요소가 포함된 함수를 호출하고, 이터러블의 모든 요소가 포함된 새 목록이 반환됩니다.

암호:

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

산출:

Python에서 목록을 반복하는 방법

이해:

람다 num: num은 목록과 함께 map 함수에 대한 입력으로 제공됩니다. 이 함수는 목록의 모든 단일 요소를 가져와 수락한 다음 반환합니다. map() 함수는 목록 요소를 하나씩 람다 함수에 전달하여 요소를 반환합니다.

다차원 목록을 반복하고 싶다면 어떻게 해야 할까요?

Python에는 다차원 목록에 대한 작업을 수행하도록 설계된 내장 모듈이 있습니다.

1. numpy를 얻으려면:

검색을 통해 cmd를 열고 다음 명령을 입력하여 Python과 pip가 설치되어 있는지 확인합니다.

Python 버전

핍 --버전

자바스크립트 전역 변수

Python과 PIP가 모두 시스템에 있으면 이제 라이브러리를 설치할 차례입니다.

2. 시작 메뉴에서 cmd를 엽니다.

3. 명령을 입력하십시오

pip 설치 numpy

Python에서 목록을 반복하는 방법

모든 라이브러리 패키지, 데이터 및 하위 패키지가 차례로 설치됩니다.

암호:

 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 함수를 사용하여 목록의 각 요소를 인쇄했습니다.