Sorting string values according to a custom alphabet in Python

前端 未结 3 776
醉话见心
醉话见心 2020-12-13 11:37

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

For example, I have a string alphabet which is \"bafmxpzv\" and

3条回答
  •  抹茶落季
    2020-12-13 12:07

    Instead of using index() which requires finding the index of a char, a better alternative consists in building a hash map to be used in the sorting, in order to retrieve the index directly.
    Example:

    >>> alphabet = "bafmxpzv"
    >>> a = ['af', 'ax', 'am', 'ab', 'zvpmf']
    >>> order = dict(zip(alphabet, range(len(alphabet))))
    >>> sorted(a, key=lambda word: [order[c] for c in word])
    ['ab', 'af', 'am', 'ax', 'zvpmf']
    

提交回复
热议问题