[Tutor] improve the code
Peter Otten
__peter__ at web.de
Tue Nov 1 17:14:28 CET 2011
lina wrote:
>> sorted(new_dictionary.items())
>
> Thanks, it works, but there is still a minor question,
>
> can I sort based on the general numerical value?
>
> namely not:
> :
> :
> 83ILE 1
> 84ALA 2
> 8SER 0
> 9GLY 0
> :
> :
>
> rather 8 9 ...83 84,
>
> Thanks,
You need a custom key function for that one:
>>> import re
>>> def gnv(s):
... parts = re.split(r"(\d+)", s)
... parts[1::2] = map(int, parts[1::2])
... return parts
...
>>> items = [("83ILE", 1), ("84ALA", 2), ("8SER", 0), ("9GLY", 0)]
>>> sorted(items, key=lambda pair: (gnv(pair[0]), pair[1]))
[('8SER', 0), ('9GLY', 0), ('83ILE', 1), ('84ALA', 2)]
More information about the Tutor
mailing list