logo

Jak inicializovat seznam v Pythonu?

Jakýkoli objekt Pythonu může být obsažen ve skupině uspořádaných hodnot v seznamu Python. Protože seznam je proměnná datová struktura v Pythonu, můžeme přidat, odebrat nebo změnit existující hodnoty v tomto kontejneru. Na rozdíl od sad seznam umožňuje mnoho instancí stejné hodnoty a s každou zachází jako s jinou položkou. V tomto tutoriálu se naučíme, jak inicializovat objekt seznamu v Pythonu.

Inicializujte seznamy pomocí hranatých závorek

Použití hranaté závorky je jedním ze způsobů, jak inicializovat seznam bez hodnot, pokud chceme v Pythonu vytvořit prázdný seznam bez hodnot. K inicializaci seznamu potřebujeme pouze zadat pár hranatých závorek s hodnotami položek nebo bez nich.

Kód

 # Python program to show how to initialize a list using square brackets # Initializing an empty list list_ = [] print('An empty list: ', list_) # Initializing a list with some values list_ = [1, 3, 5, 7] print('A non-Empty list: ', list_) 

Výstup:

 An empty list: [] A non-Empty list: [1, 3, 5, 7] 

Použití vestavěné funkce list() k inicializaci seznamu

Funkce list() v Pythonu vytváří seznam, iterovatelný objekt. Proto je to další způsob, jak vytvořit prázdný seznam Pythonu bez jakýchkoli dat v tomto kódovacím jazyce.

příkaz java if

Iterovatelný objekt, sekvence, která umožňuje iteraci, nebo kontejner mohou být iterovatelné. Pokud není zadán žádný vstup, vytvoří se nový prázdný seznam.

Kód

jak zřetězit řetězce v javě
 # Python program to show how to initialize a list using the built-in list function # Initializing an empty list list_ = list() print('An empty list: ', list_) # Initializing a non-empty list list_ = list([1, 2, 3]) print('A non-empty list: ', list_) 

Výstup:

 An empty list: [] A non-empty list: [1, 2, 3] 

Metoda hranatých závorek je upřednostňována před vestavěnou funkcí list(), protože je jasnější a názornější.

Použití List Comprehensions k inicializaci seznamu

K nastavení výchozích parametrů seznamu můžeme použít metodu porozumění seznamu. Obsahuje výraz uzavřený v hranatých závorkách, příkaz for a volitelný příkaz if, který může nebo nemusí následovat. Jakoukoli položku, kterou chceme přidat do seznamu, lze zapsat jako výraz. Výraz by byl 0, pokud by uživatel inicializoval seznam s nulami.

Porozumění seznamu je elegantní, přímočarý a dobře známý přístup ke konstrukci seznamu založeného na iterátoru.

Kód

 # Python program to show how to initialize a list using list comprehension # Initializing a list list_ = [item for item in range(10)] print('The list was created using list comprehension: ', list_) 

Výstup:

 The list was created using list comprehension: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Tato technika inicializuje seznamy mnohem rychleji než smyčky for a while v Pythonu.

Inicializujte seznam Python pomocí operátoru *

Dalším způsobem, jak inicializovat seznam v Pythonu, je použití operátoru *. Vytváří seznam s více hodnotami. Syntaxe použití tohoto operátoru je [element] * n. Zde n je počet, kolikrát chceme opakovat prvek v seznamu.

výběr řazení java

Tato metoda pomáhá, když chceme inicializovat seznam předdefinovaných délek.

Kód

 # Python program to show how to use the * operator to initialize a list list_ = [5]*10 print (list) 

Výstup:

 [5, 5, 5, 5, 5, 5, 5, 5, 5] 

Tato metoda je velmi efektivní a nejrychlejší způsob, jak vytvořit seznam. Čas, který metody zaberou, porovnáme později v tomto tutoriálu.

25 c až k

Jedinou nevýhodou použití tohoto operátoru k inicializaci seznamu v Pythonu je, když musíme vytvořit 2D seznam, protože tato metoda vytvoří pouze mělký seznam, tj. vytvoří jediný objekt seznamu a všechny indexy se na něj budou vztahovat. objekt, který bude velmi nepohodlný. To je důvod, proč používáme porozumění seznamu, když musíme vytvářet 2D seznamy.

Použití a for Loop a append()

Vytvoříme prázdný seznam a spustíme cyklus for pro přidání položek pomocí funkce append() seznamu.

Kód

 # Python program to show how to use a for loop to initialize a list arr = [] for i in range(1000): arr.append(0) 

Použití smyčky While k inicializaci seznamu

K inicializaci seznamu můžeme použít cyklus while stejně jako cyklus for.

Kód

 # Python program to initialize a list using a while loop # Creating an empty list array = [] # Declaring counter variables i = 0 # Starting a while loop while(i <10): array.append(0) i +="1" print(array) < pre> <p> <strong>Output:</strong> </p> <pre> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] </pre> <h2>Time Complexity</h2> <p>Let us now see how long each of the described approaches will take. We will initialize a list of 100000 elements 1000 times. We will calculate the average time each method takes to perform this task.</p> <p> <strong>Code</strong> </p> <pre> # Python program to see the time taken by various methods to initialize a list # importing the time module to calculate the time taken by a chunk of code import time # initializing the lists for various methods forLoop = [] whileLoop = [] listComprehension = [] starOperator = [] # repeating the process of generating a list of 100000 elements 500 times # Then calculate the average time taken by the methods for i in range(1000): # starting time of the execution begin = time.time() # declaring an empty list list_ = [] # running a for loop and iterating it 100000 times for i in range(100000): list_.append(0) # stoping time of the execution end = time.time() forLoop.append(end - begin) # starting time of the execution begin = time.time() # declaring an empty list list_ = [] i = 0 # COunter variable # running a while loop and iterating it 100000 times while i <100000: 100000 list_.append(0) i +="1" end="time.time()" whileloop.append(end - begin) begin="time.time()" # using a list comprehension to initialize the for in range(100000)] listcomprehension.append(end astrick (*) operator * staroperator.append(end print('the average execution time of loop is: ', sum(forloop) 1000) while sum(whileloop) sum(listcomprehension) taken operator: sum(staroperator) < pre> <p> <strong>Output:</strong> </p> <pre> The average execution time of for loop is: 0.01166958212852478 The average execution time of the while loop is: 0.01916465663909912 The average execution time of list comprehension is: 0.005084690093994141 The average execution time was taken of * operator: 0.00028331947326660156 </pre> <p>We can see that for and while loops take almost the same execution time. However, for loop is a little better than the while loop.</p> <p>List comprehension shows much better performance than the for and while loops. It is 2-3 times faster than the loops. Thus, list comprehension is much more efficient than the append() function of the lists.</p> <p>The * operator has shown the best performance out of all the four methods.</p> <hr></100000:></pre></10):>

Časová složitost

Podívejme se nyní, jak dlouho bude každý z popsaných přístupů trvat. 1000krát inicializujeme seznam 100 000 prvků. Vypočítáme průměrnou dobu, kterou každá metoda potřebuje k provedení tohoto úkolu.

np kde

Kód

 # Python program to see the time taken by various methods to initialize a list # importing the time module to calculate the time taken by a chunk of code import time # initializing the lists for various methods forLoop = [] whileLoop = [] listComprehension = [] starOperator = [] # repeating the process of generating a list of 100000 elements 500 times # Then calculate the average time taken by the methods for i in range(1000): # starting time of the execution begin = time.time() # declaring an empty list list_ = [] # running a for loop and iterating it 100000 times for i in range(100000): list_.append(0) # stoping time of the execution end = time.time() forLoop.append(end - begin) # starting time of the execution begin = time.time() # declaring an empty list list_ = [] i = 0 # COunter variable # running a while loop and iterating it 100000 times while i <100000: 100000 list_.append(0) i +="1" end="time.time()" whileloop.append(end - begin) begin="time.time()" # using a list comprehension to initialize the for in range(100000)] listcomprehension.append(end astrick (*) operator * staroperator.append(end print(\'the average execution time of loop is: \', sum(forloop) 1000) while sum(whileloop) sum(listcomprehension) taken operator: sum(staroperator) < pre> <p> <strong>Output:</strong> </p> <pre> The average execution time of for loop is: 0.01166958212852478 The average execution time of the while loop is: 0.01916465663909912 The average execution time of list comprehension is: 0.005084690093994141 The average execution time was taken of * operator: 0.00028331947326660156 </pre> <p>We can see that for and while loops take almost the same execution time. However, for loop is a little better than the while loop.</p> <p>List comprehension shows much better performance than the for and while loops. It is 2-3 times faster than the loops. Thus, list comprehension is much more efficient than the append() function of the lists.</p> <p>The * operator has shown the best performance out of all the four methods.</p> <hr></100000:>

Vidíme, že smyčky for a while trvají téměř stejnou dobu provádění. Smyčka for je však o něco lepší než smyčka while.

Porozumění seznamu ukazuje mnohem lepší výkon než smyčky for a while. Je 2-3x rychlejší než smyčky. Pochopení seznamu je tedy mnohem efektivnější než funkce append() seznamů.

Operátor * prokázal nejlepší výkon ze všech čtyř metod.