logo

Com inicialitzar una llista en Python?

Qualsevol objecte de Python es pot contenir en un grup de valors ordenats en una llista de Python. Com que la llista és una estructura de dades mutable a Python, podem afegir, eliminar o alterar els valors existents en aquest contenidor. A diferència dels conjunts, la llista permet nombroses instàncies del mateix valor i tracta cadascun com un element diferent. En aquest tutorial, aprendrem a inicialitzar un objecte de llista a Python.

Inicialitzeu les llistes utilitzant els claudàtors

L'ús d'un claudàtor és una manera d'iniciar una llista sense valors si volem construir una llista buida en Python sense valors. Per inicialitzar una llista, només hem d'especificar un parell de claudàtors amb o sense valors d'element.

Codi

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

Sortida:

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

Ús de la funció list() integrada per inicialitzar una llista

La funció list() de Python construeix la llista, un objecte iterable. Per tant, aquesta és una altra manera de crear una llista de Python buida sense cap dada en aquest llenguatge de codificació.

Un objecte iterador, una seqüència que permet la iteració o un contenidor poden ser iterables. Es construeix una nova llista buida si no es dóna cap entrada.

apilar en ds

Codi

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

Sortida:

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

El mètode de claudàtors es prefereix a la funció list() integrada perquè és més clara i il·lustrativa.

Ús de llistes de comprensió per inicialitzar una llista

Podem utilitzar l'enfocament de comprensió de llista per establir els paràmetres predeterminats de la llista. Comprèn una expressió entre claudàtors, una declaració for i una declaració if opcional que pot seguir o no. Qualsevol element que vulguem afegir a la llista es pot escriure com una expressió. L'expressió seria 0 si l'usuari inicialitzés la llista amb zeros.

scan.next java

La comprensió de llistes és un enfocament elegant, senzill i conegut per construir una llista basada en un iterador.

Codi

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

Sortida:

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

Aquesta tècnica inicialitza les llistes molt més ràpidament que els bucles for i while de Python.

Inicialitzeu una llista de Python amb l'operador *

Una altra manera d'iniciar una llista a Python és utilitzar l'operador *. Crea una llista amb diversos valors. La sintaxi d'utilitzar aquest operador és [element] * n. Aquí n és el nombre de vegades que volem repetir l'element de la llista.

Aquest mètode ajuda quan volem inicialitzar una llista de longituds predefinides.

Codi

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

Sortida:

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

Aquest mètode és molt eficient i la manera més ràpida de crear una llista. Compararem el temps que triguen els mètodes més endavant en aquest tutorial.

L'únic inconvenient d'utilitzar aquest operador per inicialitzar una llista de Python és quan hem de crear una llista 2D, ja que aquest mètode només crearà una llista poc profunda, és a dir, crearà un únic objecte de llista, i tots els índexs faran referència a això. objecte que serà molt inconvenient. És per això que utilitzem la comprensió de llistes quan hem de crear llistes 2D.

string compara java

Utilitzant un bucle for i append()

Crearem una llista buida i executarem un bucle for per afegir elements mitjançant la funció append() de la llista.

Codi

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

Ús d'un bucle While per inicialitzar una llista

Podem utilitzar un bucle while tal com hem utilitzat per al bucle per inicialitzar una llista.

Codi

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

Complexitat temporal

Vegem ara quant de temps trigarà cadascun dels enfocaments descrits. Inicialitzarem una llista de 100000 elements 1000 vegades. Calcularem el temps mitjà que triga cada mètode a realitzar aquesta tasca.

Codi

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

Podem veure que els bucles for i while triguen gairebé el mateix temps d'execució. Tanmateix, el bucle for és una mica millor que el bucle while.

La comprensió de la llista mostra un rendiment molt millor que els bucles for i while. És 2-3 vegades més ràpid que els bucles. Per tant, la comprensió de llistes és molt més eficient que la funció append() de les llistes.

L'operador * ha mostrat el millor rendiment dels quatre mètodes.