如何对具有不同顺序的字符串列表进行排序?

时间:2016-05-20 20:37:49

标签: python list sorting character

我正在用Python编写一个函数,可以对我的列表进行排序。问题是我不希望它与sorted()方法使用的顺序相同。我尝试使用sorting()方法,但是当我对这个字符串进行排序时,它就像这样:

0123456789abcdefghijklmnopqrstuvwxyzßàáäåæçèéêìíîñòóôöøùúüžα

我希望它的顺序是:

0123456789aàáäåæbcçdeèéêfghiìíîjklmnñoòóôöøpqrsßtuùúüvwxyzžα

现在,我有一个这样的列表(例子):

list = ['x', 'h', 'ê', 'ø', '5', 'ž', 'z', 'α', '3', '1']

我想要这样排序。如果我使用sorted()方法,它将如下所示:

['1', '3', '5', 'h', 'x', 'z', 'ê', 'ø', 'ž', 'α']

但我希望它与我之前给出的字符串的顺序相同。

1 个答案:

答案 0 :(得分:6)

我们的想法是以指定的顺序将每个char与索引相关联,并使用字符串字符的索引来进行顺序比较。

注意:仅适用于Python 3

排序一个字符串

/**
 * Generates a well formed key using the following algorithm:
 * 1. base64_encode the key first to make sure all characters are valid
 * 2. Check length of result, less than 250 then return it
 * 3. Length of result more than 250 then create a key that is md5($validKey).sha1($validKey).strlen($validKey)
 */
private function createWellFormedKey($key) {
    // Get rid of all spaces, control characters, etc using base64
    $validKey = base64_encode($key);

    $validKeyLength = strlen($validKey);
    // 250 is the maximum memcached can handle
    if (strlen($validKey) < 250) {
        return $validKey;
    }

    $validKey = md5($validKey).sha1($validKey).$validKeyLength;
    return $validKey;
}

对任意长度的字符串进行排序

ORDER = "0123456789aàáäåæbcçdeèéêfghiìíîjklmnñoòóôöøpqrsßtuùúüvwxyzžα"
# associate each char with the index in the string
# this makes sort faster for multiple invocations when compared with
# ORDER.index(c)
POS = {c:p for (p, c) in enumerate(ORDER)}

lst = ['x', 'h', 'ê', 'ø', '5', 'ž', 'z', 'α', '3', '1']

lst.sort(key = lambda c: POS[c])
# or, suggested by wim
lst.sort(key = POS.get)

输出:

class MyStrOrder:
    def __init__(self, inner):
        self.inner = inner

    def __lt__(self, other):
        for i in range(min(len(self.inner), len(other.inner))):
            a = POS.get(self.inner[i])
            b = POS.get(other.inner[i])
            if a != b:
                return a < b
        return len(self.inner) < len(other.inner)

lst = ["abc", "ab", "aá"]
lst.sort()
print(lst)

lst = ["abc", "ab", "aá"]
lst.sort(key = MyStrOrder)
print(lst)