Zkontrolujte délku seznamu v Pythonu ve 3 snadných krocích

V tomto článku uvidíme, jak zkontrolovat délku seznamu v některých snadných krocích a analyzovat, který z nich je lepší.

Co je Python List?

Seznam je kolekce polí v Pythonu, která je schopna ukládat více datových typů. Do seznamu může uložit celé číslo, plovoucí číslo, řetězec, logickou hodnotu nebo dokonce seznam.

int_list = [1, 2, 3, 4, 5]

print(int_list) # output -> [1, 2, 3, 4, 5]

float_list = [1.1, 2.2, 3.3, 4.4, 5.5]

print(float_list) # output -> [1.1, 2.2, 3.3, 4.4, 5.5]

string_list = ['Geekflare', 'Cloudflare', 'Amazon']

print(string_list) # output -> ['Geekflare', 'Cloudflare', 'Amazon']

boolean_list = [True, False]

print(boolean_list) # output -> [True, False]

nested_list = [[1, 2], [1.1, 2.2], ['Geekflare', 'Cloudflare'], [True, False]]

print(nested_list) # [[1, 2], [1.1, 2.2], ['Geekflare', 'Cloudflare'], [True, False]]

different_datatype_list = [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

print(different_datatype_list) # output -> [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

Seznamy Pythonu lze vytvořit pomocí hranatých závorek nebo funkce konstruktoru seznamu.

square_bracket_list = [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

print(square_bracket_list) # output -> [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

constructor_list = list((1, 1.1, 'etechblog.cz', True, [1, 1.1, 'Geekflare', True]))

print(constructor_list) # output -> [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

Výše uvedený seznam hranatých závorek je seznam vytvořený pomocí hranatých závorek([]), constructor_list je seznam vytvořený pomocí konstruktoru seznamu. Oba vytvářejí pouze stejný výstup seznamu.

  Jak připnout tweet někoho jiného do svého profilu

Seznam lze měnit, povolit v něm duplikáty a být přístupný pomocí indexu.

Metody k nalezení délky seznamu

  • vestavěná funkce len().
  • metoda length_hint od operátora
  • vlastní funkce a počítadlo

Metoda 1: vestavěná funkce len().

Len() je funkce vestavěná v pythonu, která se používá k nalezení délky seznamu a také pro další iterovatelné položky, jako je Set, Tuples, Dictionary.

Příklad Snippet

languages = ['Python', 'Java', 'C++', 'PHP', 'nodeJS']

languages_length = len(languages)

print('Length of the Language List is: ',languages_length)

Výstup

Length of the Language List is:  5

Doufám, že máte nainstalovaný Python, pokud ne, můžete k procvičení kódu použít online kompilátor Pythonu.

Metoda 2: metoda length_hint od operátora

length_hint se používá k vrácení délky iterovatelného objektu (jako je seznam, sada, n-tice, slovník). Je k dispozici uvnitř modulu operátora python. Není k dispozici jako ostatní vestavěné operátory.

  Aktualizace Disku Google vám umožní uzamknout soubory pomocí čtyřmístného přístupového kódu

Příklad Snippet

import operator

languages = ['Python', 'Java', 'C++', 'PHP', 'nodeJS']

languages_length = operator.length_hint(languages)

print('Length of the Language List using Operator is: ',languages_length)

Výstup

Length of the Language List using Operator is:  5

Metoda 3: Vlastní funkce a počítadlo

V této metodě pro zjištění délky seznamu použijeme tradiční metodu pomocí for-loop a counter.

Za tímto účelem napíšeme funkci v pythonu. který bere seznam nebo jinou iterovatelnou jako argument a vrací délku iterovatelné.

Vlastní funkce Snippet

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

Příklad Snippet

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

languages = ['Python', 'Java', 'C++', 'PHP', 'nodeJS']

languages_length = iterable_count(languages)

print('Length of the Language List using Custom function is: ',languages_length)

Výstup

Length of the Language List using Custom function is:  5

Analýza těchto 3 metod

Analýza výkonu pro velký seznam

import timeit # for benchmarking & profiling
import operator

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

integer_list = list(range(1, 9999999))

#length check using len()
start_time = timeit.default_timer()
len_length = len(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using len() is: ',len_length)

#length check using operator.length_hint
start_time = timeit.default_timer()
len_length = operator.length_hint(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using length_hint is: ',len_length)

start_time = timeit.default_timer()
iterable_count_length = iterable_count(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using Custom function is: ',iterable_count_length)

Výstup

3.957189619541168e-06 Length of the Integer List using len() is:  9999998
3.0621886253356934e-06 Length of the Integer List using length_hint is:  9999998
0.4059128537774086 Length of the Integer List using Custom function is:  9999998

Jak můžeme vidět, length_hint je rychlejší (3.0621886253356934e-06), když jsou data v milionech. Je to proto, že nápovědu délky používá běhové prostředí CPythonu. Kde se tomu říká python wrapper.

  9 nejlepších převaděčů MP4 na GIF

Analýza výkonu pro malý seznam

import timeit # for benchmarking & profiling
import operator

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

integer_list = list(range(1, 100))

#length check using len()
start_time = timeit.default_timer()
len_length = len(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using len() is: ',len_length)

#length check using operator.length_hint
start_time = timeit.default_timer()
len_length = operator.length_hint(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using length_hint is: ',len_length)

start_time = timeit.default_timer()
iterable_count_length = iterable_count(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using Custom function is: ',iterable_count_length)

Výstup

7.813796401023865e-07 Length of the Integer List using len() is:  99
1.1278316378593445e-06 Length of the Integer List using length_hint is:  99
3.462657332420349e-06 Length of the Integer List using Custom function is:  99

Jak vidíme, len() je rychlejší (7.813796401023865e-07), když jsou data v tisících nebo méně.

V obou případech naše vlastní funkce s čítačem zabere více času než obě metody.

Závěr

V tomto článku rozumíme různým způsobům, jak zkontrolovat délku seznamu a jak rychle zkontrolovat délku seznamu.