Resumen de estructuras de datos en Python

Tuplas, Listas, Sets, Diccionarios, Listas de comprehension, funciones, clases

Vamos a ver ejemplos de estructuras de datos en Python.

Tuplas

Son el tipo mas simple de estructura, puede almacenar en una misma variables mas de un dato.


In [2]:
x = (1,2,3,0,2,1)

In [3]:
x


Out[3]:
(1, 2, 3, 0, 2, 1)

In [4]:
x = (0, 'hola', (1,2))

In [5]:
x


Out[5]:
(0, 'hola', (1, 2))

In [14]:
len(x)


Out[14]:
3

Una vez que guardan en una tupla datos, pueden accesarlos con indices en brackets. En python los indices comienzan en cero.


In [6]:
x[0]


Out[6]:
0

In [7]:
x[1]


Out[7]:
'hola'

In [8]:
x[2]


Out[8]:
(1, 2)

In [11]:
x[0:3]


Out[11]:
(0, 'hola', (1, 2))

In [12]:
x[0:2]


Out[12]:
(0, 'hola')

Que tienen de malo las tuplas y porque necesitariamos algomas? Son inmutables.


In [13]:
x[1] = 'adios'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-f0e52fbd8b21> in <module>()
----> 1 x[1] = 'adios'

TypeError: 'tuple' object does not support item assignment

In [15]:
id(x)


Out[15]:
2235293596336

In [16]:
x = (0, 'adios', (1,2))

In [17]:
id(x)


Out[17]:
2235293702544

Listas

Son elementos que pueden cambiar de valores y de tamano una vez creados, son las estructuras mas usadas. En vez de usar parentesis usan brackets.


In [18]:
x = [1,2,3]

In [19]:
x[0] = 'hola'

In [20]:
x


Out[20]:
['hola', 2, 3]

In [21]:
x.append('nuevo valor')

In [22]:
x


Out[22]:
['hola', 2, 3, 'nuevo valor']

In [28]:
x.insert(2, 'valor intermedio')

In [31]:
x.pop(0)


Out[31]:
2

In [32]:
x


Out[32]:
['valor intermedio', 3, 2, 'nuevo valor']

Que es mas rapido, tuplas o listas?


In [37]:
import timeit
timeit.timeit('x = (1,2,3,4,5,6)')


Out[37]:
0.056244844442698394

In [38]:
timeit.timeit('x=[1,2,3,4,5,6]')


Out[38]:
0.16208327181655946

Atencion para los usuarios de R: referencia o asignacion?


In [57]:
x = [1,2,3] # asignacion

In [63]:
y = [0, x] # referencia

In [64]:
y


Out[64]:
[0, [1, 2, 3]]

In [65]:
x[0] = -1 # asignamos otra lista a x

In [66]:
y


Out[66]:
[0, [-1, 2, 3]]

Diccionarios

En una GRAN cantidad de problemas, quieren almacenar claves y asignarle a cada clave un valor. Un mejor nombre para diccionario (ejemplo jaja) es "directorio telefonico".


In [68]:
dir_tel = {'juan': 553423523,  'pedro': 243252345, 'itam':'is fun'}

In [71]:
dir_tel['juan']


Out[71]:
553423523

In [72]:
dir_tel['itam']


Out[72]:
'is fun'

In [73]:
dir_tel.keys()


Out[73]:
dict_keys(['juan', 'pedro', 'itam'])

In [74]:
dir_tel.values()


Out[74]:
dict_values([553423523, 243252345, 'is fun'])

Sets

son conjuntos matematicos


In [77]:
A = {1,2,3}
B = {2,3,4}

In [78]:
A | B # union


Out[78]:
{1, 2, 3, 4}

In [79]:
A & B # interseccion


Out[79]:
{2, 3}

In [80]:
A - B # diferencia de conjuntos


Out[80]:
{1}

In [81]:
B - A


Out[81]:
{4}

In [82]:
A ^ B # diferencia simetrica


Out[82]:
{1, 4}

Condicionales y Loops, For, While, If, Elif

El truco para hacer loops en python es la funcion range


In [83]:
range(1000)


Out[83]:
range(0, 1000)

In [85]:
for i in range(5): # for (i in 0:(n-1))
    print(i)


0
1
2
3
4

In [90]:
for i in range(10):
    if i % 2 == 0: # operador de modulo (residuo tras division)
        print(str(i) + ' par') # str convierte numero en string
    else:
        print(str(i) + ' impar')


0 par
1 impar
2 par
3 impar
4 par
5 impar
6 par
7 impar
8 par
9 impar

In [91]:
i = 0
while i < 10:
    print(i)
    i = i + 1


0
1
2
3
4
5
6
7
8
9

Booleanos, short circuits


In [92]:
True and True


Out[92]:
True

In [93]:
True and False


Out[93]:
False

In [94]:
True or True


Out[94]:
True

In [95]:
True or False


Out[95]:
True

In [96]:
2 > 3 or 1 < 2


Out[96]:
True

In [97]:
(2 > 3) and (1 < 2)


Out[97]:
False

Clases


In [125]:
class Person:
    def __init__(self, first, last):
        self.first = first # campos
        self.last = last       
    def greet(self, add_msg = ""): # mas metodos
        print('hello ' + self.first + ' ' + add_msg)

In [126]:
juan = Person('juan', 'dominguez')

In [127]:
type(juan)


Out[127]:
__main__.Person

In [128]:
juan.first


Out[128]:
'juan'

In [129]:
juan.last


Out[129]:
'dominguez'

In [130]:
pedro = Person('pedro', 'gonzalez')

In [131]:
pedro.first


Out[131]:
'pedro'

In [132]:
pedro.last


Out[132]:
'gonzalez'

In [133]:
pedro.greet('my friend')


hello pedro my friend

In [ ]:


In [ ]: