Simple exercise
Gregory Ewing
greg.ewing at canterbury.ac.nz
Thu Mar 10 18:24:08 EST 2016
Rodrick Brown wrote:
> if m.group(1) not in od.keys():
> od[m.group(1)] = int(m.group(2))
> else:
> od[m.group(1)] += int(od.get(m.group(1),0))
Others have pointed out what's wrong with this, but here's
a general tip: Don't repeat complicated subexpressions
such as m.group(1). Doing so makes the code hard to read
and therefore hard to spot errors in (and less efficient
as well, although that's a secondary consideration).
Instead, pull them out and give them meaningful names.
Doing so with the above code gives:
name = m.group(1)
value = m.group(2)
if name not in od.keys():
od[name] = int(value)
else:
od[name] += int(od.get(name, 0))
Now it's a lot eaier to see that you haven't used the
value anywhere in the second case, which should alert
you that something isn't right.
--
Greg
More information about the Python-list
mailing list