dict generator question

Boris Borcic bborcic at gmail.com
Fri Sep 19 06:15:58 EDT 2008


Gerard flanagan wrote:
> George Sakkis wrote:
..
>>
>> Note that this works correctly only if the versions are already sorted
>> by major version.
>>
> 
> Yes, I should have mentioned it. Here's a fuller example below. There's 
> maybe better ways of sorting version numbers, but this is what I do.

Indeed, your sort takes George's objection too litterally, what's needed for a 
correct endresult is only that major versions be grouped together, and this is 
most simply obtained by sorting the input data in (default) string order, is it 
not ?

> 
> 
> data = [ "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.1.1.1", "1.3.14.5", 
> "1.3.21.6" ]
> 
> from itertools import groupby
> import re
> 
> RXBUILDSORT = re.compile(r'\d+|[a-zA-Z]')
> 
> def versionsort(s):
>     key = []
>     for part in RXBUILDSORT.findall(s.lower()):
>         try:
>             key.append(int(part))
>         except ValueError:
>             key.append(ord(part))
>     return tuple(key)
> 
> data.sort(key=versionsort)
> print data
> 
> datadict = \
> dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
> print datadict
> 
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list