[Tutor] improve the code

Peter Camilleri pdc.cse at gmail.com
Fri Nov 4 03:58:30 CET 2011


Not sure if that is what you are after since you are calling
re.split() using items when Peter was using re.split() on a single
item within items

so instead of this
parts = re.split(r"(\d+)", str(items))
try specifying just one item, like this
parts = re.split(r"(\d+)", items[0])

On Fri, Nov 4, 2011 at 1:42 PM, lina <lina.lastname at gmail.com> wrote:
> On Fri, Nov 4, 2011 at 10:39 AM, lina <lina.lastname at gmail.com> wrote:
>> On Wed, Nov 2, 2011 at 12:14 AM, Peter Otten <__peter__ at web.de> wrote:
>>> 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)]
>>
>>
>> Thanks, I can follow the procedure and get the exact results, but
>> still don't understand this part
>>
>> parts = re.split(r'"(\d+)",s)
>>
>> r"(\d+)", sorry,
>>
>>>>> items
>> [('83ILE', 1), ('84ALA', 2), ('8SER', 0), ('9GLY', 0)]
>>
>>
>>>>> parts = re.split(r"(\d+)",items)
>> Traceback (most recent call last):
>>  File "<pyshell#78>", line 1, in <module>
>>    parts = re.split(r"(\d+)",items)
>>  File "/usr/lib/python3.2/re.py", line 183, in split
>>    return _compile(pattern, flags).split(string, maxsplit)
>> TypeError: expected string or buffer
>
> Sorry, now works.
>
> parts = re.split(r"(\d+)", str(items))
>>
>> Thanks,
>>>
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list