Sort string values ​​according to custom alphabet in Python

I am looking for an efficient way to sort a list of strings according to a custom alphabet.

For example, I have a string alphabet "bafmxpzv"and a list of strings consisting only of the characters contained in this alphabet.

I need a way to sort this list similarly to other common types, but using this custom alphabet. How can i do this?

+5
source share
2 answers

Let me create an alphabet and a list of words:

In [32]: alphabet = "bafmxpzv"

In [33]: a = ['af', 'ax', 'am', 'ab', 'zvpmf']

Now sort them according to where the letters appear in alphabet:

In [34]: sorted(a, key=lambda word: [alphabet.index(c) for c in word])
Out[34]: ['ab', 'af', 'am', 'ax', 'zvpmf']

The above sortings are in the correct order.

sorted . sorted : cmp, key reverse:

  • cmp . , cmp It, . , , , , . cmp .

  • key, spedified, , , python . .

    key alphabet.

  • reverse, true, .

:

In [35]: sorted(a, key=lambda word: [alphabet.index(c) for c in word[0]])
Out[35]: ['af', 'ax', 'am', 'ab', 'zvpmf']

, . , key . key:

In [2]: key=lambda word: [alphabet.index(c) for c in word[0]]

In [3]: key('af')
Out[3]: [1]

In [4]: key('ax')
Out[4]: [1]

, key , af ax. . - sorted , af ax.

+5

, , , , , , , :

def acmp (a,b):
 la = len(a)
 lb = len(b)
 lm = min(la,lb)
 p = 0
 while p < lm:
    pa = alphabet.index(a[p])
    pb = alphabet.index(b[p])
    if pa > pb:
        return 1
    if pb > pa:
        return -1
    p = p + 1

 if la > lb:
    return 1
 if lb > la:
    return -1
 return 0

mylist = ['baf', 'bam', 'pxm']
mylist.sort(cmp = acmp)
+1

All Articles