Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Joaquim Gabarro
gabarro@cs.upc.edu
Computer Science
Universitat Politècnica de Catalunya
Listas→Diccionarios
Ficheros
Listas→Diccionarios
Ejemplo: Agenda
Tenemos el esquema:
def crear_agenda(lista):
agenda = {}
for x in lista:
# llenar agenda
return agenda
Veamos como llenar agenda.
Sea x= ["Juan", "610000001", "Balmes 111"]
hay que añadir a agenda:
’Juan’: [’610000001’, ’Balmes 111’]
La clave es ’Juan’ el valor es [’610000001’,’Balmes 111’]
Obtenemos la clave y el valor a partir de x:
agenda = {}
for x in lista:
agenda[x[0]] = x[1:] # cuidado si hay nombres repetidos
return agenda
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
L = [["Juan", "610000001", "Balmes 111"],
["Pedro", "610000002", "Parı́s 222"],
["Antonio", "610000003", "Valencia 333"],
["Edu", "610000004", "Mallorca 444"]]
print("imprimir L: ", L)
a = crear_agenda(L)
print("agenda: ", a)
print("datos de Juan: ", a["Juan"])
print("telefono de Juan", a["Juan"][0])
Exemple: Inverted Index
https://en.wikipedia.org/wiki/Inverted_index
An inverted index (also referred to as postings file or inverted
file) is an index data structure storing a mapping from content,
such as words or numbers, to its locations in a database file...
Pag 387 of How to Think Like a Computer Scientist: Python 3
starts the following Index (really and Inverted Index)
A
abbreviated assignment,92
abecedarian series,116
abstract data type (ADT),323
accumulator,297
algorithm, 2,7, 106,107
...
B
baked animation,246
bar chart, 63
base case, 252,256
...
Let us consider the following toy exercise.
def toy_inverted_index(text):
word=text.split()
inverted_file={}
for k in range(len(word)):
if word[k] in inverted_file:
inverted_file[word[k]].append(k)
else:
inverted_file[word[k]] = [k]
return inverted_file
Ejemplo: locos por los anagramas
https://es.wikipedia.org/wiki/Anagrama
https://es.wikipedia.org/wiki/Alfabeto_griego
def future_keys(L):
keys=[]
for w in L:
if ordena(w) not in keys:
keys.append(ordena(w))
return keys
def locos_por_anagramas(L):
# 1. conunto de claves
keys=future_keys(L)
# 2. dic anagramas vacio
anagramas={}
for key in keys:
anagramas[key]=[]
# 3. llenamos dic anagramas
for palabra in L:
clave = ordena(palabra)
anagramas[clave].append(palabra)
# 4. dic numeros: version final
numeros={}
i=0
for clave in anagramas:
if len(anagramas[clave])>1:
numeros[i]=anagramas[clave]
i=i+1
return numeros
def main():
my_first_write_file("my_first_file.txt")
main()
After executing:
>>>
RESTART: C:... \my_first_write_file.py
>>>
The first is the name of the file, the second is the mode.
I Mode "w" means that we are opening the file for writing.
I With mode "w", if there is no file my first file.txt, it
will be created. If there is one, it will be replaced by the file
we are writing.
I To put data in the file we invoke the write()
myfile.write("My first file written from Python\n"
I Closing the file handle tells the system that we are done
and makes the disk file available.
Example: Reading my first file
I Now that the file exists on our disk, we can open it,
I this time for reading,
I and read all the lines in the file, one at a time.
I This time, the mode argument is r for reading
def main():
my_first_read_file("my_first_file.txt")
main()
def sort_friends(my_friends):
f = open(my_friends, "r")
xs = f.readlines()
f.close()
xs.sort()
g = open("sorted_friends.txt", "w")
for v in xs:
g.write(v)
g.close()
The readlines() reads all the lines and returns a list of strings:
[’kim kim@intro.program.caos\n’, ’maria mario@must.program.success\n’,
’jorge jorge@python.fortran.linux\n’, ’edelmira edelmira@c.plus.plus\n’,
’jordi jordi@advocat.proves.compila\n’]
To run the program we also need:
def my_read_file(file):
mynewhandle = open(file, "r")
theline = mynewhandle.readline()
while len(theline)>0:
print(theline, end="")
theline = mynewhandle.readline()
mynewhandle.close()
def main():
sort_friends("my_friends.txt")
my_read_file("sorted_friends.txt")
Executing we get:
>>>
RESTART: C:\Users...\sort_friends.py
edelmira edelmira@c.plus.plus
jordi jordi@advocat.proves.compila
jorge jorge@python.fortran.linux
kim kim@intro.program.caos
maria mario@must.program.success
>>>
Following sort friends extended.py.
Some prints() are added to trace the program’s evolution
def sort_friends(my_friends):
f = open(my_friends, "r")
xs = f.readlines()
print("\n--- a list ----\n")
print(xs)
f.close()
print("\n--- the sorted list ----\n")
xs.sort()
print(xs)
g = open("sorted_friends.txt", "w")
for v in xs:
g.write(v)
g.close()
def my_read_file(file):
mynewhandle = open(file, "r")
theline = mynewhandle.readline()
print("\n--- print the new file ----\n")
while len(theline)>0:
print(theline, end="")
theline = mynewhandle.readline()
mynewhandle.close()
def main():
sort_friends("my_friends.txt")
my_read_file("sorted_friends.txt")
RESTART: C:...\sort_friends_extended.py
edelmira edelmira@c.plus.plus
jordi jordi@advocat.proves.compila
jorge jorge@python.fortran.linux
kim kim@intro.program.caos
maria mario@must.program.success
>>>