Mar 27
A few interesting things about Python that I had forgotten come from
here.
I’ve modified the examples.
First, you can use an instance’s namespace to give an interesting way to print
strings. Sometimes this will be better:
# Basic version. print 'My name is +s and I am +d.' + (p.name, p.age) # Advanced version. print 'My name is +(name)s and I am +(age)d.' + p.__dict__
There is also the enumerate function, which returns (index, item) pairs. For
example,
{}{py}
for (index, item) in enumerate(items):
print index, item
Dictionaries have a setdefault method. Consider these alternative pieces of
code:
# Naive piece of code. for (cat, amount) in data: if cat not in d: d[cat] = 0 d[cat] += amount # Simpler piece of code. for (cat, amount) in data: d.setdefault(cat, 0) d[cat] += amount # A cunning third option: setdefault also gets. for (cat, amount) in data: d[cat] = d.setdefault(cat, 0) + amount
But, better than all of these optons is the new defaultdict in Python 2.5.
from collections import defaultdict d = defaultdict(generator_function) # Example like those above. d = defaultdict(lambda: 0)
Finally, generator expressions: say we want to sum a large list that we generate
on the fly (ie, we don’t care about the list):
(I didn’t find much difference in evaluation time, though.)
sum(i**2 for i in xrange(1e5))