Strutture di dati
Versione italiana
Le strutture dati sono fondamentali in Python per organizzare e manipolare informazioni. Ecco una spiegazione dettagliata di quelle che hai menzionato:
Liste
Le liste sono collezioni ordinate e mutabili (modificabili) di elementi.
-
Creazione, accesso agli elementi, slicing:
- Creazione:
lista = [1, 2, 3, 4]
- Accesso:
lista[0]
(primo elemento),lista[-1]
(ultimo elemento) - Slicing:
lista[1:3]
(elementi dall'indice 1 al 2),lista[:2]
(dall'inizio all'indice 1),lista[2:]
(dall'indice 2 alla fine)
Esempio:
lista = [10, 20, 30, 40] print(lista[1]) # Output: 20 print(lista[1:3]) # Output: [20, 30] - Creazione:
-
Metodi delle liste:
append()
: aggiunge un elemento alla fine.remove()
: rimuove la prima occorrenza di un valore.sort()
: ordina la lista.pop()
: rimuove e restituisce l'elemento all'indice specificato.insert()
: inserisce un elemento in una posizione specifica.
Esempio:
lista = [3, 1, 4, 2] lista.append(5) # Aggiunge 5 alla fine lista.sort() # Ordina la lista: [1, 2, 3, 4, 5] lista.remove(3) # Rimuove il numero 3 print(lista) # Output: [1, 2, 4, 5]
Tuple
Le tuple sono collezioni ordinate ma immutabili (non modificabili).
-
Differenze tra liste e tuple:
- Le tuple sono definite con parentesi tonde:
tupla = (1, 2, 3)
- Non puoi modificare una tupla dopo la creazione (nessun
append
,remove
, ecc.). - Sono più efficienti in termini di memoria rispetto alle liste.
Esempio:
tupla = (1, 2, 3) print(tupla[0]) # Output: 1 # tupla[0] = 10 # Errore: le tuple sono immutabili - Le tuple sono definite con parentesi tonde:
Dizionari
I dizionari sono collezioni non ordinate (fino a Python 3.6) di coppie chiave-valore.
-
Creazione, accesso, modifica:
- Creazione:
dizionario = {"chiave1": "valore1", "chiave2": "valore2"}
- Accesso:
dizionario["chiave1"]
(restituisce "valore1") - Modifica:
dizionario["chiave1"] = "nuovo_valore"
Esempio:
diz = {"nome": "Mario", "età": 30} print(diz["nome"]) # Output: Mario diz["età"] = 31 # Modifica il valore - Creazione:
-
Metodi dei dizionari:
keys()
: restituisce le chiavi.values()
: restituisce i valori.items()
: restituisce coppie chiave-valore.get()
: restituisce il valore associato a una chiave, o un valore predefinito se la chiave non esiste.
Esempio:
diz = {"nome": "Mario", "età": 30} print(diz.keys()) # Output: dict_keys(['nome', 'età']) print(diz.values()) # Output: dict_values(['Mario', 30]) print(diz.items()) # Output: dict_items([('nome', 'Mario'), ('età', 30)])
Set
I set sono collezioni non ordinate e senza duplicati.
-
Operazioni su insiemi:
- Unione:
set1 | set2
oset1.union(set2)
- Intersezione:
set1 & set2
oset1.intersection(set2)
- Differenza:
set1 - set2
oset1.difference(set2)
Esempio:
set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1 | set2) # Unione: {1, 2, 3, 4, 5} print(set1 & set2) # Intersezione: {3} print(set1 - set2) # Differenza: {1, 2} - Unione:
Altri tipi di dati
-
range
:- Genera una sequenza di numeri.
- Esempio:
range(5)
genera i numeri da 0 a 4.
-
enumerate
:- Restituisce sia l'indice che il valore durante l'iterazione.
- Esempio:lista = ["a", "b", "c"] for indice, valore in enumerate(lista): print(indice, valore)
-
zip
:- Combina più iterabili in una sequenza di tuple.
- Esempio:lista1 = [1, 2, 3] lista2 = ["a", "b", "c"] for numero, lettera in zip(lista1, lista2): print(numero, lettera)
English version
Data Structures
Data structures are fundamental to Python for organizing and manipulating information. Here is a detailed explanation of the ones you mentioned:
Lists
Lists are ordered and mutable (editable) collections of elements.
- Creation, access to elements, slicing:
- Creation:
list = [1, 2, 3, 4]
- Access:
list[0]
(first element),list[-1]
(last element) - Slicing:
list[1:3]
(elements from index 1 to 2),list[:2]
(from beginning to index 1),list[2:]
(from index 2 to end)
Example:
list = [10, 20, 30, 40]
print(list[1]) # Output: 20
print(list[1:3]) # Output: [20, 30]
- List methods:
append()
: Adds an element to the end.remove()
: Removes the first occurrence of a value.sort()
: Sorts the list.pop()
: Removes and returns the element at the specified index.insert()
: Inserts an element at a specified position.
Example:
list = [3, 1, 4, 2]
list.append(5) # Adds 5 to the end
list.sort() # Sorts the list: [1, 2, 3, 4, 5]
list.remove(3) # Removes the number 3
print(list) # Output: [1, 2, 4, 5]
Tuples
Tuples are sorted but immutable (not modifiable) collections.
- Differences between lists and tuples:
- Tuples are defined with parentheses:
tuple = (1, 2, 3)
- You cannot modify a tuple after creation (no
append
,remove
, etc.). - They are more memory efficient than lists.
Example:
tuple = (1, 2, 3)
print(tuple[0]) # Output: 1
# tuple[0] = 10 # Error: tuples are immutable
Dictionaries
Dictionaries are unordered collections (up to Python 3.6) of key-value pairs.
- Create, access, modify:
- Create:
dictionary = {"key1": "value1", "key2": "value2"}
- Access:
dictionary["key1"]
(returns "value1") - Modify:
dictionary["key1"] = "new_value"
Example:
diz = {"name": "Mario", "age": 30}
print(diz["name"]) # Output: Mario
diz["age"] = 31 # Modify the value
- Dictionary methods:
keys()
: Returns keys.values()
: Returns values.items()
: Returns key-value pairs.get()
: Returns the value associated with a key, or a default value if the key does not exist.
Example:
dic = {"name": "Mario", "age": 30}
print(dic.keys()) # Output: dict_keys(['name', 'age'])
print(dic.values()) # Output: dict_values(['Mario', 30])
print(dic.items()) # Output: dict_items([('name', 'Mario'), ('age', 30)])
Sets
Sets are unordered and duplicate-free collections.
- Set Operations:
- Union:
set1 | set2
orset1.union(set2)
- Intersection:
set1 & set2
orset1.intersection(set2)
- Difference:
set1 - set2
orset1.difference(set2)
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # Union: {1, 2, 3, 4, 5}
print(set1 & set2) # Intersection: {3}
print(set1 - set2) # Difference: {1, 2}
Other data types
range
:
- Generates a sequence of numbers.
- Example:
range(5)
generates numbers from 0 to 4.
enumerate
:
- Returns both index and value during iteration.
- Example:
list = ["a", "b", "c"]
for index, value in enumerate(list):
print(index, value)
zip
:
- Combines multiple iterables into a sequence of tuples.
- Example:
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for number, letter in zip(list1, list2):
print(number, letter)
Commenti
Posta un commento