如何对具有不同顺序的字符串列表进行排序? [英] How to sort a list of strings with a different order?

查看:83
本文介绍了如何对具有不同顺序的字符串列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a function in Python which can sort my list. The problem is that I don't want it in the same order that the sorted() method used. I tried using the sorting() method, but when I sort this string, which I it comes out like this:

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

我希望它进入的顺序是:

The order I want it to be in is:

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

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

Now, I've got a list like this (example):

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

我想对它进行排序.如果我使用 sorted()方法,它将看起来像这样:

And I want so sort it. If I'd use the sorted() method, it would look like this:

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

但是我希望它与我之前给定的字符串顺序相同.

But I want it to be in the same order as the string I gave before.

推荐答案

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

The idea is to associate to each char the index in the specified order and use the indexes of the string chars to do the order comparison.

注意:仅适用于Python 3

Note: only works with Python 3

排序一个字符字符串

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)

输出:

['ab', 'abc', 'aá']
['aá', 'ab', 'abc']

这篇关于如何对具有不同顺序的字符串列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆