sorting - Python: comparing strings with numerals. Decoding radio call-signs -


i've got feeling core concept of might repeat question can't find it.

okay, have bunch of radio callsigns , want find country of origin here.

i've tried basic comparison find country location way python orders numerals , characters vs way callsigns different:

in python "zr1" < "zra" == true false in callsign convention.

is there anyway can change python's ordering "... 7 < 8 < 9 < < b ..." "... x < y < z < 0 < 1 < 2 ..."?

you create dict mapping characters positions in "correct" ordering , compare lists of positions:

import string order = {e: i, e in enumerate(string.ascii_uppercase + string.digits)} positions = lambda s: [order[c] c in s]  def cmp_callsign(first, second):     return cmp(positions(first), positions(second))  # (cmp removed in python 3) 

usage:

>>> positions("zr1") [25, 17, 27] >>> cmp("zr1", "zra")  # normal string comparison -1 >>> cmp_callsign("zr1", "zra")  # callsign comparison 1 >>> sorted(["ar1", "zr1", "zra"], key=positions) ['ar1', 'zra', 'zr1'] 

to make comparison automatic, create class callsign , override __cmp__ or __eq__ , __lt__ methods accordingly:

class callsign:     def __init__(self, code):         self.code = code     def __lt__(self, other):         return positions(self.code) < positions(other.code)   a, b, c = callsign("zra"), callsign("zr1"), callsign("zr9") print(a < b < c)  # true print(a < c < b)  # false 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -