-
Notifications
You must be signed in to change notification settings - Fork 0
/
comprehensions and assignments.py
79 lines (54 loc) · 1.02 KB
/
comprehensions and assignments.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
x = 10
y = -10
# Bad
tmp = y
y = x
x = tmp
# Better
x, y = y, x
# Bad
print(int('1'))
# Better
try:
print(int('1'))
except:
print('Conversion failed!')
else:
print('Conversion successful')
finally:
print('Executes even when exception fires!')
shelters = ['Tent', 'Caravan', 'House', 'Castle']
# Bad, assumes four parameters
smallest, _, _, largest = shelters
# Better
smallest = shelters[0]
largest = shelters[-1]
# Better
smallest, *rest, largest = shelters
import string
cities = [
'Groningen',
'Marseille',
'Buenos Aires',
'Mumbai'
]
populations = [
197823,
852516,
2890151,
12442373
]
# Bad
d = {}
for city, population in zip(cities, populations):
d[string.capwords(city)] = population
print(d)
# Better, dictionary comprehension
d = { string.capwords(city) : population for city, population in zip(cities, populations) }
print(d)
# Better, preserves order
import collections
d = collections.OrderedDict()
for city, population in zip(cities, populations):
d[string.capwords(city)] = population
print(d)