logo

Python에서 목록의 길이를 찾는 방법

Python 프로그래밍의 필수적인 부분인 목록은 모든 Python 사용자가 배워야 하며 해당 유틸리티 및 작업에 대한 지식을 갖는 것이 필수적이며 항상 장점입니다.

많은 작업이 목록에서 수행되지만 이 문서에서는 목록의 길이에 대해 설명합니다. 목록의 길이는 목록에 포함된 요소의 수를 의미합니다. 우리는 목록의 길이를 구하는 8가지 방법을 살펴볼 것입니다. 파이썬 .



예:

  Input:   lst = [10,20,30,40]   Output:   4   Explanation:   The output is 4 because the length of the list is 4.>

Python에서 목록의 길이 찾기

이 기사에서 다룰 방법은 다음과 같습니다.

1. len() 함수를 사용하여 목록의 길이 찾기

파이썬 오직() 함수는 Python에 내장된 함수입니다. len 함수의 괄호 안에 객체를 전달하여 객체의 길이를 찾는 데 사용할 수 있습니다.



파이썬3






# Python len()> li>=> [>10>,>20>,>30>]> n>=> len>(li)> print>(>'The length of list is: '>, n)>

>

>

자바 메인 메소드

산출:

The length of list is: 3>

시간 복잡도: O(n), 여기서 n은 목록의 길이입니다.
보조 공간: 오(1)

2. 순진한 방법을 사용하여 목록의 길이 찾기

이 방법에서는 루프를 실행하고 목록의 마지막 요소까지 카운터를 증가시켜 개수를 알 수 있습니다. 이는 현재의 다른 기술이 없을 때 사용할 수 있는 가장 기본적인 전략입니다.

파이썬3




# Initializing list> test_list>=> [>1>,>4>,>5>,>7>,>8>]> # Printing test_list> print>(>'The list is : '> +> str>(test_list))> # Finding length of list using loop> # Initializing counter> counter>=> 0> for> i>in> test_list:> ># incrementing counter> >counter>=> counter>+> 1> # Printing length of list> print>(>'Length of list using naive method is : '> +> str>(counter))>

>

>

산출:

The list is : [1, 4, 5, 7, 8] Length of list using naive method is : 5>

시간 복잡도: 에)
보조 공간: 오(1)

3. length_hint() 메소드를 사용하여 목록의 길이 찾기

이 기술은 목록 길이를 찾는 덜 알려진 기술입니다. 이 특정 메서드는 연산자 클래스에 정의되어 있으며 아니요를 알려줄 수도 있습니다. 목록에 있는 요소의 수입니다. 여기서는 len() 및 length_hint()를 사용하여 목록의 길이를 찾습니다.

파이썬3




from> operator>import> length_hint> # Initializing list> test_list>=> [>1>,>4>,>5>,>7>,>8>]> # Printing test_list> print>(>'The list is : '> +> str>(test_list))> # Finding length of list using len()> list_len>=> len>(test_list)> # Finding length of list using length_hint()> list_len_hint>=> length_hint(test_list)> # Printing length of list> print>(>'Length of list using len() is : '> +> str>(list_len))> print>(>'Length of list using length_hint() is : '> +> str>(list_len_hint))>

>

npm 캐시 제거

>

출력 :

The list is : [1, 4, 5, 7, 8] Length of list using len() is : 5 Length of list using length_hint() is : 5>

4. sum() 함수를 사용하여 목록의 길이 찾기

합계 내부에서 반복을 사용하고 각 반복마다 1을 더하고 반복이 끝나면 목록의 전체 길이를 얻습니다.

파이썬3




# Initializing list> test_list>=> [>1>,>4>,>5>,>7>,>8>]> # Printing test_list> print>(>'The list is : '> +> str>(test_list))> # Finding length of list> # using sum()> list_len>=> sum>(>1> for> i>in> test_list)> # Printing length of list> print>(>'Length of list using len() is : '> +> str>(list_len))> print>(>'Length of list using length_hint() is : '> +> str>(list_len))>

>

>

산출:

The list is : [1, 4, 5, 7, 8] Length of list using len() is : 5 Length of list using length_hint() is : 5>

5. List Comprehension을 사용하여 목록의 길이 찾기

라는 목록을 초기화합니다. 테스트_목록 일부 값을 사용하여 length라는 변수를 0으로 초기화합니다. list comprehension을 사용하여 test_list의 각 요소에 대한 시퀀스를 생성합니다.

그러면 test_list와 길이가 같은 목록이 생성됩니다. 이제 sum() 함수를 사용하여 생성된 목록의 모든 항목을 합산합니다. 목록 이해 . 길이 변수에 합계를 할당합니다. 길이 변수를 인쇄합니다.

파이썬3




# Define the list to be used for the demonstration> test_list>=> [>1>,>4>,>5>,>7>,>8>]> # Calculate the length of the list using a list comprehension and the sum function> # The list comprehension generates a sequence of ones for each element in the list> # The sum function then sums all the ones to give the length of the list> length>=> sum>(>1> for> _>in> test_list)> # Print the length of the list> print>(>'Length of list using list comprehension is:'>, length)>

>

>

산출

업캐스팅
Length of list using list comprehension is: 5>

시간 복잡도: 목록 이해는 test_list의 길이와 동일한 길이의 새 목록을 생성합니다. 그런 다음 sum() 함수는 이 목록을 반복하여 합계를 계산합니다. 따라서 이 알고리즘의 시간 복잡도는 O(N)입니다. 여기서 N은 test_list의 길이입니다.
보조 공간: 알고리즘은 목록 이해를 사용하여 test_list의 길이와 동일한 길이를 가진 새로운 목록을 생성합니다. 따라서 보조 공간 복잡도도 O(N)입니다. 여기서 N은 test_list의 길이입니다.

6. 재귀를 사용하여 목록의 길이 찾기

우리는 재귀 함수 그건 목록을 가져가는 거야 첫 번째 입력으로 사용하고 자신을 재귀적으로 호출하여 목록이 빌 때까지 첫 번째 요소를 제외하는 목록 조각을 전달합니다.

기본 사례는 목록이 비어 있는 경우이며, 이 경우 함수는 0을 반환합니다. 그렇지 않으면 목록의 나머지 부분에서 함수를 호출한 결과에 1을 추가합니다.

파이썬3




# Define a function to count the number of elements in a list using recursion> def> count_elements_recursion(lst):> ># Base case: if the list is empty, return 0> >if> not> lst:> >return> 0> ># Recursive case: add 1 to the count of the remaining elements in the list> >return> 1> +> count_elements_recursion(lst[>1>:])> # Test the function with a sample list> lst>=> [>1>,>2>,>3>,>4>,>5>]> print>(>'The length of the list is:'>, count_elements_recursion(lst))> # Output: The length of the list is: 5>

>

알파베타 가지치기

>

산출

The length of the list is: 5>

시간 복잡도: O(n) 여기서 n은 목록의 길이입니다. 이는 함수가 n개의 재귀 호출을 수행하고 각각 O(1) 시간이 걸리며 재귀 호출 외부의 각 수준에서 O(1) 작업이 수행되기 때문입니다.
공간 복잡도: O(n) 여기서 n은 목록의 길이입니다. 이는 함수가 재귀 호출로 인해 호출 스택에 n개의 스택 프레임을 생성하기 때문입니다.

7. enumerate() 함수를 사용하여 목록의 길이 찾기

파이썬 낱낱이 세다() 메서드는 iterable에 카운터를 추가하고 열거형 개체 형식으로 반환합니다.

파이썬3




# python code to find the length> # of list using enumerate function> list1>=> [>1>,>4>,>5>,>7>,>8>]> s>=> 0> for> i, a>in> enumerate>(list1):> >s>+>=> 1> print>(s)>

>

>

산출

5>

8. 컬렉션을 사용하여 목록의 길이 찾기

또는 다음을 사용할 수도 있습니다. 합집합() 함수의 value() 메소드와 함께 컬렉션 목록의 길이를 가져오는 카운터 개체입니다.

파이썬3




from> collections>import> Counter> # Initializing list> test_list>=> [>1>,>4>,>5>,>7>,>8>]> # Finding length of list using Counter()> list_len>=> sum>(Counter(test_list).values())> print>(>'Length of list using Counter() is:'>, list_len)> # This code is contributed by Edula Vinay Kumar Reddy>

>

>

산출

Length of list using Counter() is: 5>

시간 복잡도: O(n), 여기서 n은 목록의 길이입니다. 이는 Counter() 함수를 길이 n의 목록에 적용할 때 O(n)의 시간 복잡도를 갖고, value() 메서드와 sum() 함수를 적용할 때 둘 다 O(n)의 시간 복잡도를 갖기 때문입니다. 길이 n의 목록으로.
공간 복잡도: O(n)은 Counter() 함수로서 n개의 키-값 쌍이 있는 사전을 생성하며, 각각은 목록의 요소와 개수를 나타냅니다. 이 사전은 O(n) 공간을 차지합니다.

성능 분석: 순진함 vs Python len() vs Python length_hint()

대안 중에서 선택할 때는 항상 하나를 선택해야 하는 타당한 이유가 있어야 합니다. 이 섹션에서는 더 나은 사용 선택을 제공하기 위해 모든 항목을 실행하는 데 걸리는 시간을 분석합니다.

파이썬3




from> operator>import> length_hint> import> time> # Initializing list> test_list>=> [>1>,>4>,>5>,>7>,>8>]> # Printing test_list> print>(>'The list is : '> +> str>(test_list))> # Finding length of list> # using loop> # Initializing counter> start_time_naive>=> time.time()> counter>=> 0> for> i>in> test_list:> ># incrementing counter> >counter>=> counter>+> 1> end_time_naive>=> str>(time.time()>-> start_time_naive)> # Finding length of list> # using len()> start_time_len>=> time.time()> list_len>=> len>(test_list)> end_time_len>=> str>(time.time()>-> start_time_len)> # Finding length of list> # using length_hint()> start_time_hint>=> time.time()> list_len_hint>=> length_hint(test_list)> end_time_hint>=> str>(time.time()>-> start_time_hint)> # Printing Times of each> print>(>'Time taken using naive method is : '> +> end_time_naive)> print>(>'Time taken using len() is : '> +> end_time_len)> print>(>'Time taken using length_hint() is : '> +> end_time_hint)>

>

>

mysql 사용자 목록

산출:

The list is : [1, 4, 5, 7, 8] Time taken using naive method is : 2.6226043701171875e-06 Time taken using len() is : 1.1920928955078125e-06 Time taken using length_hint() is : 1.430511474609375e-06>

아래 이미지를 보면 소요시간이 확실히 알 수 있습니다. 순진한>> length_hint()> len() , 그러나 소요 시간은 OS 및 해당 매개변수에 따라 크게 달라집니다.

두 번의 연속 실행에서는 대조적인 결과를 얻을 수 있습니다. 실제로 때로는 순진한 실행이 세 번 중 가장 짧은 시간을 소비합니다. 가능한 6개의 순열이 모두 가능합니다.

순진한> len()> length_hint()

순진한> len()=length_hint()

순진한> length_hint()>len()

순진한> length_hint()> len()

우리는 Python에서 목록의 길이를 구하는 8가지 방법을 논의했습니다. 또한 어떤 방법이 가장 좋은지 확인하기 위해 성능 분석도 수행했습니다.

위의 방법 중 하나를 사용하여 목록의 길이를 찾을 수 있습니다. 목록 길이를 찾는 것은 거대한 목록을 처리하고 항목 수를 확인하려는 경우 매우 유용합니다.

더 많은 Python 목록 페이지를 확인하세요: