Dictionary¶
In [48]:
# inizializzo con curl brakets
d = {'Norway':'Oslo','Sweden':'Sockholm','France':'Paris'}
# aggiungo un elemento
d['Germany'] = 'Berlin'
print(d['Germany'])
# inizializzo con dict
temps = dict(Oslo='13',London=15.4,Paris=17.5)
for citta, temperatura in sorted(temps.items()):
print(f"La temperatura media a {citta} è {temperatura}°C")
# cerco se una determinata chiave esiste
if 'Berlin' in temps:
print('Berlin:', temps['Berlin'])
else:
print('No temperature data for Berlin')
# cancello uno degli elementi
del temps['Oslo']
print(temps)
# per accedere a chiave e valore separatamente
# temps.keys() --- temps.values()
for temp in temps.values():
print(temp)
# posso copiare
t2 = temps.copy()
Berlin
La temperatura media a London è 15.4°C
La temperatura media a Oslo è 13°C
La temperatura media a Paris è 17.5°C
No temperature data for Berlin
{'London': 15.4, 'Paris': 17.5}
15.4
17.5
A Dictionary of Polynomials¶
$$\large p(x) = -1+x^2+3x^7$$
In [57]:
poly = {0:-1,2:1,7:3}
x = 1
def eval_poly_dict(poly, x):
sum = 0.0
for power in poly:
sum += poly[power]*x**power
return sum
print(eval_poly_dict(poly, x))
3.0
In [59]:
poly = {0:-1,2:1,7:3}
x = 1
def eval_poly_dict(poly, x):
#Python’s sum can add elements of an iterator
return sum(poly[power]*x**power for power in poly)
print(eval_poly_dict(poly, x))
3
Posso fare anche partendo da una List¶
In [61]:
p = [-1,0,1,0,0,0,0,3]
x = 1
def eval_poly_list(poly, x):
sum = 0
for power in range(len(poly)):
sum += poly[power]*x**power
return sum
print(eval_poly_list(p, x))
3
Posso fare ache mediante Enumerate¶
Qui dobbiamo memorizzare tutti gli zeri¶
In [66]:
p = [-1,0,1,0,0,0,0,3]
x = 1
def eval_poly_list_enum(poly, x):
sum = 0
# power, coeff sono due tuple
for power, coeff in enumerate(poly):
sum += coeff*x**power
return sum
print(eval_poly_list(p, x))
3
Se vogliamo un sistema "sparse"¶
In [85]:
p = {0:-1,2:1,7:3}
def eval_poly_dict(poly, x):
#Python’s sum can add elements of an iterator
return sum(poly[power]*x**power for power in poly)
print(eval_poly_dict(p, x=1))
3
Reading File Data to a Dictionary¶
In [88]:
# creo un dizionario vuoto, poi riempio
with open('deg2.txt','r') as infile:
temps = {}
for line in infile:
city, temp = line.split()
city = city[:-1]
temps[city] = float(temp)
print(temps)
{'Oslo': 21.8, 'London': 18.1, 'Berlin': 19.0, 'Paris': 23.0, 'Rome': 26.0, 'Helsinki': 17.8}
Strings¶
In [103]:
s = 'Berlin: 18.4 C at 4 pm'
for s_ in s:
print(s_,end=' ')
print('')
print(s.find('Berlin'))
print(s.find('pm'))
print(s.find('Oslo'))
print('Berlin' in s)
s.replace('Berlin','Bonn')
B e r l i n : 1 8 . 4 C a t 4 p m 0 20 -1 True
Out[103]:
'Bonn: 18.4 C at 4 pm'
Splitting and Joining Strings¶
In [112]:
s = 'Berlin: 18.4 C at 4 pm'
print(s.split(':'))
print(s.split())
['Berlin', ' 18.4 C at 4 pm'] ['Berlin:', '18.4', 'C', 'at', '4', 'pm']
In [118]:
strings = ['Newton', 'Secant','Biscection']
print(', '.join(strings))
Newton, Secant, Biscection
In [124]:
"""
Tromso Norway 69.6351 18.9920 52436
Molde Norway 62.7483 7.1833 18594
Oslo Norway 59.9167 10.7500 835000
Stockholm Sweden 59.3508 18.0973 1264000
Uppsala Sweden 59.8601 17.6400 133117
"""
cities = {}
with open('cities.txt') as infile:
for line in infile:
words = line.split()
name = ', '.join(words[:2])
data = {'lat': float(words[2]), 'long':float(words[3])}
data['pop'] = int(words[4])
cities[name] = data
print(cities)
{'Tromso, Norway': {'lat': 69.6351, 'long': 18.992, 'pop': 52436}, 'Molde, Norway': {'lat': 62.7483, 'long': 7.1833, 'pop': 18594}, 'Oslo, Norway': {'lat': 59.9167, 'long': 10.75, 'pop': 835000}, 'Stockholm, Sweden': {'lat': 59.3508, 'long': 18.0973, 'pop': 1264000}, 'Uppsala, Sweden': {'lat': 59.8601, 'long': 17.64, 'pop': 133117}}
String Manupulation¶
In [129]:
t = '1st line\r\n2nd line\r\n3rd line' #Windows
print(t)
t = '1st line\n2nd line\n3rd line' #Mac, Unix format
print(t.splitlines())
t = '1st line\r\n2nd line\r\n3rd line' #Windows
print(t.splitlines()) #cross platform!
1st line 2nd line 3rd line ['1st line', '2nd line', '3rd line'] ['1st line', '2nd line', '3rd line']
String are constant, immutable objects !¶
Posso aggiungere pezzi o procedere con replace()¶
In [140]:
s = ' text with leading/trailibg spaces '
print('"'+s.strip()+'"')
print('"'+s.lstrip()+'"')
print('"'+s.rstrip()+'"')
"text with leading/trailibg spaces" "text with leading/trailibg spaces " " text with leading/trailibg spaces"
In [150]:
s = 'Berlin: 18.4 C at 4 pm'
print(s.startswith('Berlin'))
print(s.endswith('am'))
print(s.lower())
print(s.upper())
True False berlin: 18.4 c at 4 pm BERLIN: 18.4 C AT 4 PM
Reading a pair of numbers from a file¶
In [159]:
pairs = []
#list of (n1, n2) pairs of numbers
with open('pairs.txt', 'r') as lines:
for line in lines:
words = line.split()
for word in words:
word = word[1:-1] #strip off parentheses
#print(word)
n1, n2 = word.split(',')
n1 = float(n1); n2 = float(n2)
pair = (n1, n2)
pairs.append(pair)
print(pairs)
[(1.3, 0.0), (-1.0, 2.0), (3.0, -1.5), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0), (0.0, -0.01), (10.5, -1.0), (2.5, -2.5)]
In [ ]: