Generator slower than iterator?

Arnaud Delobelle arnodel at googlemail.com
Tue Dec 16 13:17:14 EST 2008


bearophileHUGS at lycos.com writes:

> This can be a little faster still:
>
> match_counter = defaultdict(int)
> for line in fileinput.input(sys.argv[1:]):
>     ip = line.split(None, 1)[0]
>     match_counter[ip] += 1
>
> Bye,
> bearophile

Or maybe (untested):

match_counter = defaultdict(int)
for line in fileinput.input(sys.argv[1:]):
    ip = line[:line.index(' ')]
    match_counter[ip] += 1

Or even (untested, I've never tried this ;):

from itertools import count
match_counter = defaultdict(count)
for line in fileinput.input(sys.argv[1:]):
    ip = line[:line.index(' ')]
    match_counter[ip].next()

match_total = dict((key, val()) for key, val in match_counter.iteritems())

Obviously the variable 'ip' could be removed in all cases.

-- 
Arnaud



More information about the Python-list mailing list