In questo tutorial imparerai a conoscere il modulo array Python, la differenza tra array ed elenchi e come e quando usarli con l'aiuto di esempi.
Nota: quando le persone dicono array in Python, il più delle volte, stanno parlando di elenchi Python . In tal caso, visita il tutorial dell'elenco Python.
In questo tutorial, ci concentreremo su un modulo denominato array
. Il array
modulo ci permette di memorizzare una raccolta di valori numerici.
Creazione di array Python
Per creare un array di valori numerici, dobbiamo importare il array
modulo. Per esempio:
import array as arr a = arr.array('d', (1.1, 3.5, 4.5)) print(a)
Produzione
matrice ('d', (1.1, 3.5, 4.5))
Qui abbiamo creato un array di float
tipo. La lettera d
è un codice di tipo. Questo determina il tipo di array durante la creazione.
I codici di tipo comunemente usati sono elencati come segue:
Codice | Tipo C. | Tipo Python | Byte min |
---|---|---|---|
b | firmato char | int | 1 |
B | carattere non firmato | int | 1 |
u | Py_UNICODE | Unicode | 2 |
h | firmato a breve | int | 2 |
H | corto non firmato | int | 2 |
i | firmato int | int | 2 |
I | unsigned int | int | 2 |
l | firmato a lungo | int | 4 |
L | non firmato a lungo | int | 4 |
f | galleggiante | galleggiante | 4 |
d | Doppio | galleggiante | 8 |
Non discuteremo diversi tipi di C in questo articolo. Useremo due codici di tipo in questo intero articolo: i
per interi e d
per float.
Nota : il u
codice tipo per i caratteri Unicode è obsoleto dalla versione 3.3. Evita di usarne il più possibile.
Accesso agli elementi dell'array Python
Usiamo gli indici per accedere agli elementi di un array:
import array as arr a = arr.array('i', (2, 4, 6, 8)) print("First element:", a(0)) print("Second element:", a(1)) print("Last element:", a(-1))
Produzione
Primo elemento: 2 Secondo elemento: 4 Ultimo elemento: 8
Nota : l'indice inizia da 0 (non 1) in modo simile agli elenchi.
Affettare array Python
Possiamo accedere a una serie di elementi in un array utilizzando l'operatore di affettamento :
.
import array as arr numbers_list = (2, 5, 62, 5, 42, 52, 48, 5) numbers_array = arr.array('i', numbers_list) print(numbers_array(2:5)) # 3rd to 5th print(numbers_array(:-5)) # beginning to 4th print(numbers_array(5:)) # 6th to end print(numbers_array(:)) # beginning to end
Produzione
array ('i', (62, 5, 42)) array ('i', (2, 5, 62)) array ('i', (52, 48, 5)) array ('i', (2 , 5, 62, 5, 42, 52, 48, 5))
Modifica e aggiunta di elementi
Gli array sono mutabili; i loro elementi possono essere modificati in modo simile alle liste.
import array as arr numbers = arr.array('i', (1, 2, 3, 5, 7, 10)) # changing first element numbers(0) = 0 print(numbers) # Output: array('i', (0, 2, 3, 5, 7, 10)) # changing 3rd to 5th element numbers(2:5) = arr.array('i', (4, 6, 8)) print(numbers) # Output: array('i', (0, 2, 4, 6, 8, 10))
Produzione
array ('i', (0, 2, 3, 5, 7, 10)) array ('i', (0, 2, 4, 6, 8, 10))
Possiamo aggiungere un elemento all'array utilizzando il append()
metodo o aggiungere diversi elementi utilizzando il extend()
metodo.
import array as arr numbers = arr.array('i', (1, 2, 3)) numbers.append(4) print(numbers) # Output: array('i', (1, 2, 3, 4)) # extend() appends iterable to the end of the array numbers.extend((5, 6, 7)) print(numbers) # Output: array('i', (1, 2, 3, 4, 5, 6, 7))
Produzione
array ('i', (1, 2, 3, 4)) array ('i', (1, 2, 3, 4, 5, 6, 7))
Possiamo anche concatenare due array usando +
operator.
import array as arr odd = arr.array('i', (1, 3, 5)) even = arr.array('i', (2, 4, 6)) numbers = arr.array('i') # creating empty array of integer numbers = odd + even print(numbers)
Produzione
matrice ('i', (1, 3, 5, 2, 4, 6))
Removing Python Array Elements
We can delete one or more items from an array using Python's del statement.
import array as arr number = arr.array('i', (1, 2, 3, 3, 4)) del number(2) # removing third element print(number) # Output: array('i', (1, 2, 3, 4)) del number # deleting entire array print(number) # Error: array is not defined
Output
array('i', (1, 2, 3, 4)) Traceback (most recent call last): File "", line 9, in print(number) # Error: array is not defined NameError: name 'number' is not defined
We can use the remove()
method to remove the given item, and pop()
method to remove an item at the given index.
import array as arr numbers = arr.array('i', (10, 11, 12, 12, 13)) numbers.remove(12) print(numbers) # Output: array('i', (10, 11, 12, 13)) print(numbers.pop(2)) # Output: 12 print(numbers) # Output: array('i', (10, 11, 13))
Output
array('i', (10, 11, 12, 13)) 12 array('i', (10, 11, 13))
Check this page to learn more about Python array and array methods.
Python Lists Vs Arrays
In Python, we can treat lists as arrays. However, we cannot constrain the type of elements stored in a list. For example:
# elements of different types a = (1, 3.5, "Hello")
If you create arrays using the array
module, all elements of the array must be of the same numeric type.
import array as arr # Error a = arr.array('d', (1, 3.5, "Hello"))
Output
Traceback (most recent call last): File "", line 3, in a = arr.array('d', (1, 3.5, "Hello")) TypeError: must be real number, not str
When to use arrays?
Lists are much more flexible than arrays. They can store elements of different data types including strings. And, if you need to do mathematical computation on arrays and matrices, you are much better off using something like NumPy.
So, what are the uses of arrays created from the Python array module?
The array.array
type is just a thin wrapper on C arrays which provides space-efficient storage of basic C-style data types. If you need to allocate an array that you know will not change, then arrays can be faster and use less memory than lists.
A meno che non siano realmente necessari array (potrebbe essere necessario un modulo array per interfacciarsi con il codice C), l'uso del modulo array non è raccomandato.