logo

Jak zjistit délku seznamu v Pythonu

Seznam, který je nedílnou součástí programování v Pythonu, se musí naučit všichni uživatelé Pythonu a znalost jeho nástrojů a operací je zásadní a vždy výhodou.

Mnoho operací se provádí v seznamech, ale v tomto článku se budeme zabývat délkou seznamu. Délka seznamu znamená počet prvků, které má. Podíváme se na 8 různých metod, jak zjistit délku seznamu Krajta .



Příklad:

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

Najděte délku seznamu v Pythonu

Níže jsou uvedeny metody, které pokryjeme v tomto článku:

1. Najděte délku seznamu pomocí funkce len().

Krajta jen() funkce je funkce vestavěná v Pythonu. Lze jej použít k nalezení délky objektu předáním objektu do závorek funkce len.



Python3






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

>

>

Výstup:

The length of list is: 3>

Časová náročnost: O(n), kde n je délka seznamu
Pomocný prostor: O(1)

2. Najděte délku seznamu pomocí naivní metody

V této metodě stačí spustit smyčku a zvýšit počítadlo až do posledního prvku seznamu, abyste věděli jeho počet. Toto je nejzákladnější strategie, kterou lze případně použít, pokud neexistují jiné současné techniky.

Python3




# 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))>

>

>

Výstup:

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

Časová náročnost: Na)
Pomocný prostor: O(1)

náhodný v c

3. Najděte délku seznamu pomocí metody length_hint().

Tato technika je méně známá technika pro zjištění délky seznamu. Tato konkrétní metoda je definována ve třídě operátorů a může také říci ne. prvků přítomných v seznamu. Zde zjišťujeme délku seznamu pomocí len() a length_hint()

Python3




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))>

>

>

Výstup :

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

4. Najděte délku seznamu pomocí funkce sum().

Použijte iteraci uvnitř součtu a s každou iterací přidáte jednu a na konci iterace dostaneme celkovou délku seznamu.

Python3




# 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))>

>

>

Výstup:

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

5. Najděte délku seznamu pomocí funkce List Comprehension

Inicializujte volaný seznam test_list s některými hodnotami pak inicializujte proměnnou nazvanou length na 0. Použijte porozumění seznamu k vygenerování sekvence jedniček pro každý prvek v test_listu.

Tím se vytvoří seznam těch, které mají stejnou délku jako test_list. Nyní použijte funkci sum() k sečtení všech položek v seznamu generovaném pomocí porozumění seznamu . Přiřaďte součet proměnné délky. Vytiskněte proměnnou délky.

Python3




# 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)>

inkscape vs gimp

>

>

Výstup

Length of list using list comprehension is: 5>

Časová náročnost: Porozumění seznamu vytvoří nový seznam s délkou rovnou délce seznamu testů. Funkce sum() pak iteruje přes tento seznam a vypočítá součet. Proto je časová složitost tohoto algoritmu O(N), kde N je délka seznamu testů.
Pomocný prostor: Algoritmus vytvoří nový seznam jedniček s délkou rovnou délce test_listu pomocí porozumění seznamu. Složitost pomocného prostoru je tedy také O(N), kde N je délka seznamu testů.

6. Najděte délku seznamu pomocí rekurze

Můžeme použít a rekurzivní funkce to vyžaduje seznam lst jako vstup a rekurzivně volá sám sebe a předává část seznamu, který vylučuje první prvek, dokud není seznam prázdný.

Základní případ je, když je seznam prázdný, v takovém případě funkce vrátí 0. V opačném případě přidá 1 k výsledku volání funkce na zbytku seznamu.

Python3




# 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>

>

>

Výstup

The length of the list is: 5>

Časová složitost: O(n) kde n je délka seznamu. Je to proto, že funkce provádí n rekurzivních volání, z nichž každé trvá O(1) čas, a na každé úrovni mimo rekurzivní volání je také vykonána práce O(1).
Složitost prostoru: O(n) kde n je délka seznamu. Je to proto, že funkce vytváří n zásobníkových rámců na zásobníku volání kvůli rekurzivním voláním.

7. Najděte délku seznamu pomocí funkce enumerate().

Krajta vyjmenovat() metoda přidá čítač k iterovatelnému a vrátí jej ve formě výčtového objektu.

Python3




# 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)>

>

>

Výstup

python inicializační seznam
5>

8. Najděte délku seznamu pomocí kolekcí

Případně můžete také použít součet() funkce spolu s metodou values() the Sbírky Počítadlo objektu pro získání délky seznamu.

Python3




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>

>

>

Výstup

Length of list using Counter() is: 5>

Časová složitost: O(n), kde n je délka seznamu. Je to proto, že funkce Counter() má časovou složitost O(n), když je aplikována na seznam délky n, a metoda values() a funkce sum() mají při aplikaci časovou složitost O(n). na seznam délky n.
Složitost prostoru: O(n) jako funkce Counter() vytvoří slovník s n páry klíč–hodnota, z nichž každý představuje prvek a jeho počet v seznamu. Tento slovník zabírá O(n) místa.

Analýza výkonu: Naivní vs Python len() vs Python length_hint()

Při výběru mezi alternativami je vždy nutné mít pádný důvod, proč zvolit jednu před druhou. Tato část provádí časovou analýzu toho, kolik času zabere provedení všech z nich, aby bylo možné použít lepší volbu.

Python3




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)>

>

>

Výstup:

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>

Na níže uvedených obrázcích je jasně vidět, že zabraný čas je naivní>> length_hint()> len() , ale čas, který to trvá, velmi závisí na operačním systému a několika jeho parametrech.

Ve dvou po sobě jdoucích jízdách můžete získat kontrastní výsledky, ve skutečnosti někdy naivní zabere nejméně času ze tří. Všech možných 6 permutací je možných.

naivní> len()> length_hint()

naivní> len()=length_hint()

naivní> length_hint()>len()

naivní> length_hint()> len()

Probrali jsme 8 různých metod, jak zjistit délku seznamu v Pythonu. Provedli jsme také analýzu výkonu, abychom zjistili, která metoda je nejlepší.

Pro zjištění délky seznamu můžete použít kteroukoli z výše uvedených metod. Zjištění délky seznamu je velmi užitečné, když pracujete s velkými seznamy a chcete zkontrolovat počet záznamů.

podřetězec řetězce java

Podívejte se na další stránky se seznamy Pythonu: