En este tutorial, aprenderá sobre el módulo de matriz de Python, la diferencia entre matrices y listas, y cómo y cuándo usarlas con la ayuda de ejemplos.
Nota: Cuando la gente dice matrices en Python, la mayoría de las veces, están hablando de listas de Python . Si ese es el caso, visite el tutorial de la lista de Python.
En este tutorial, nos centraremos en un módulo llamado array
. El array
módulo nos permite almacenar una colección de valores numéricos.
Crear matrices de Python
Para crear una matriz de valores numéricos, necesitamos importar el array
módulo. Por ejemplo:
import array as arr a = arr.array('d', (1.1, 3.5, 4.5)) print(a)
Salida
matriz ('d', (1.1, 3.5, 4.5))
Aquí, creamos una matriz de float
tipo. La letra d
es un código de tipo. Esto determina el tipo de matriz durante la creación.
Los códigos de tipo más utilizados se enumeran a continuación:
Código | Tipo C | Tipo de Python | Bytes mínimos |
---|---|---|---|
b | char firmado | En t | 1 |
B | char sin firmar | En t | 1 |
u | Py_UNICODE | Unicode | 2 |
h | firmado corto | En t | 2 |
H | corto sin firmar | En t | 2 |
i | firmado int | En t | 2 |
I | int sin firmar | En t | 2 |
l | firmado largo | En t | 4 |
L | largo sin firmar | En t | 4 |
f | flotador | flotador | 4 |
d | doble | flotador | 8 |
No discutiremos diferentes tipos de C en este artículo. Usaremos dos códigos de tipo en todo este artículo: i
para enteros y d
para flotantes.
Nota : El u
código de tipo para caracteres Unicode está obsoleto desde la versión 3.3. Evite usar tanto como sea posible.
Acceder a los elementos de la matriz de Python
Usamos índices para acceder a elementos de una matriz:
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))
Salida
Primer elemento: 2 Segundo elemento: 4 Último elemento: 8
Nota : El índice comienza desde 0 (no 1) similar a las listas.
Cortar matrices de Python
Podemos acceder a una variedad de elementos en una matriz utilizando el operador de corte :
.
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
Salida
matriz ('i', (62, 5, 42)) matriz ('i', (2, 5, 62)) matriz ('i', (52, 48, 5)) matriz ('i', (2 , 5, 62, 5, 42, 52, 48, 5))
Cambiar y agregar elementos
Las matrices son mutables; sus elementos se pueden cambiar de forma similar a las listas.
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))
Salida
matriz ('i', (0, 2, 3, 5, 7, 10)) matriz ('i', (0, 2, 4, 6, 8, 10))
Podemos agregar un elemento a la matriz usando el append()
método, o agregar varios elementos usando el extend()
método.
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))
Salida
matriz ('i', (1, 2, 3, 4)) matriz ('i', (1, 2, 3, 4, 5, 6, 7))
También podemos concatenar dos matrices 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)
Salida
matriz ('yo', (1, 3, 5, 2, 4, 6))
Eliminar elementos de matriz de Python
Podemos eliminar uno o más elementos de una matriz usando la declaración del de Python.
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
Salida
array ('i', (1, 2, 3, 4)) Traceback (última llamada más reciente): Archivo "", línea 9, en letra impresa (número) # Error: la matriz no está definida NameError: el nombre 'número' es no definida
Podemos usar el remove()
método para eliminar el elemento dado y el pop()
método para eliminar un elemento en el índice dado.
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))
Salida
matriz ('i', (10, 11, 12, 13)) 12 matriz ('i', (10, 11, 13))
Consulte esta página para obtener más información sobre la matriz de Python y los métodos de matriz.
Python Lists Vs Arrays
En Python, podemos tratar las listas como matrices. Sin embargo, no podemos restringir el tipo de elementos almacenados en una lista. Por ejemplo:
# elements of different types a = (1, 3.5, "Hello")
Si crea matrices utilizando el array
módulo, todos los elementos de la matriz deben ser del mismo tipo numérico.
import array as arr # Error a = arr.array('d', (1, 3.5, "Hello"))
Salida
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 menos que realmente no necesite matrices (es posible que se necesite un módulo de matriz para interactuar con el código C), no se recomienda el uso del módulo de matriz.