Python: Operações com Arrays

From Wiki

Arrays em python só podem ser de apenas um tipo

Operações com Arrays

Básico

#!/usr/bin/python
from array import * 

vals = array('i',[5,9,6,7])
print vals
# array('i', [5, 6, 9, 7])

print vals[0]
# 5

vals.reverse()
print vals
# array('i', [7, 9, 6, 5])

for v in vals:
  print(v,end='')
# 7965

newArray = array(vals.typecode, (v*2 for v in vals))
print(newArray)
# array('i', [14, 18, 12, 10])

Arrays multi-dimensionais

Para arrays multi-dimensionais usamos o módulo numpy.

>>> from numpy import *
>>> arr = array([1,2,4,7,5,9])
>>> print(arr)
[1 2 4 7 5 9]
>>> print(arr.dtype)
int64
>>> arr = array([1,2,4,7,5.3])
>>> print(arr)
[ 1.   2.   4.   7.   5.3]
>>>print(arr.dtype)
float64

arange

>>> arr = arange(1,15,2)
>>> print arr
[ 1  3  5  7  9 11 13]

zeros

>>> arr = zeros(5)
>>> print arr
[ 0.  0.  0.  0.  0.]

ones

>>> arr = ones(7)
>>> print arr
[ 1.  1.  1.  1.  1.  1.  1.]
>>> arr = ones(7,int)
>>> print arr
[1 1 1 1 1 1 1]

logspace

>>> arr = logspace(1,15,2)
>>> print arr
[  1.00000000e+01   1.00000000e+15]

linspace

Cria partes

>>> arr = linspace(0,2,3) 
>>> print arr
[ 0.  1.  2.]
>>> arr = linspace(0,5,4)
>>> print arr
[ 0.          1.66666667  3.33333333  5.        ]

Ver também