Code: Alles auswählen
def without_setdefault1():
d = {}
for x in xrange(500):
for y in xrange(100):
if x not in d:
d[x] = [y]
else:
d[x].append(y)
def without_setdefault2():
d = {}
for x in xrange(500):
for y in xrange(100):
try:
d[x].append(y)
except KeyError:
d[x] = [y]
def with_setdefault():
d = {}
for x in xrange(500):
for y in xrange(100):
d.setdefault(x, []).append(y)
if __name__ == '__main__':
from timeit import Timer
def timeit(func, number):
name = func.__name__
t = Timer("%s()" % name, "from __main__ import %s" % name)
print "%s:" % name,
print "%.3fsec" % t.timeit(number)
number = 200
timeit(with_setdefault, number)
timeit(without_setdefault1, number)
timeit(without_setdefault2, number)
Code: Alles auswählen
with_setdefault: 3.404sec
without_setdefault1: 2.462sec
without_setdefault2: 2.361sec
Welche Variante nutzt ihr am meisten? Bisher nehme ich immer without_setdefault1