dict generator question

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Sep 20 04:30:58 CEST 2008

> except that it could be misleading when:
>     len(file(path))
> returns the number of lines and /not/ the length in bytes as you might
> first think! :-)

Well, file(...) returns an iterable of lines, so its len is the number
of lines :-)
I think I am able to always remember this fact.

> Anyway, here's another possible implementation using bags (multisets):

This function looks safer/faster:

def major_version(version_string):
    "convert '' to '1.2'"
    return '.'.join(version_string.strip().split('.', 2)[:2])

Another version:

import re
patt = re.compile(r"^(\d+\.\d+)")

dict_of_counts = defaultdict(int)
for ver in versions:
    dict_of_counts[patt.match(ver).group(1)] += 1

print dict_of_counts


More information about the Python-list mailing list