Em Sáb, 2006-04-01 às 08:35 -0800, Steve R. Hastings escreveu: > def tally(seq, d=None): > if d == None: > d = {} > > for x in seq: > if x in d: > d[x] += 1 > else: > d[x] = 1 > return d
Two changes: - Use "is None". - Use "try ... except" instead of "in" def tally2(seq, d=None): if d is None: d = {} for x in seq: try: d[x] += 1 except KeyError: d[x] = 1 return d It's also faster: >>> from random import choice >>> a = [] >>> for i in xrange(100000): ... a.append(choice([False, True])) ... >>> tally(a) {False: 49922, True: 50078} >>> tally2(a) {False: 49922, True: 50078} >>> from timeit import Timer >>> min(Timer(stmt='b=tally(a)', setup='from __main__ import a, tally').repeat(3, 100)) 4.2756481170654297 >>> min(Timer(stmt='b=tally2(a)', setup='from __main__ import a, tally2').repeat(3, 100)) 3.812028169631958 Maybe you don't like my version, and the gains aren't that much, but please use "is None" instead of "== None". Cheers, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list