【问题标题】:How to sort array of string and int values, multiple attributes with alphabetical and "reversed"-alphabetical order如何对字符串和 int 值的数组、具有字母顺序和“反转”字母顺序的多个属性进行排序
【发布时间】:2018-12-19 23:00:47
【问题描述】:

我有一个包含 [name, surname, int1, int2] 元素的数组,我需要按以下顺序对其进行排序:

  • int1(递减)。

  • 如果int1 相同,则按“颠倒”字母顺序按name 排序。

  • 如果name相同,则按surname字母顺序排列。

所以我有这个:

print(sorted(a, key = lambda x: [-int(x[2]), x[0], x[1]]))

我不知道如何以反向字母顺序对x[0] 进行排序 -x[0], x[0][::-1] 不适合我。

例子:

[('Petia', 'Anja', 3, 0),
 ('Vasia', 'Katia', 3, 0),
 ('Petia', 'Katia', 3, 0),
 ('Kolia', 'Alexey', 10, 0),
 ('Yana', 'Anja', 10, 0)]

[('Yana', 'Anja', 10, 0),
 ('Kolia', 'Alexey', 10, 0),
 ('Vasia', 'Katia', 3, 0),
 ('Petia', 'Anja', 3, 0),
 ('Petia', 'Katia', 3, 0)]

【问题讨论】:

  • 您是指颠倒的字母顺序,如 z->a,还是颠倒的字母顺序,如颠倒字符串中的字母顺序?
  • @user3483203 z->是的。我添加了一些示例

标签: python string list sorting alphabetical-sort


【解决方案1】:

您可以创建一个具有 < 实现的类(< 是所有 CPythons sorted 需要的 - 如果您使用另一个 Python 实现,您可能需要额外的比较运算符)。这允许完全控制“排序”。例如:

class Sorter(object):
    def __init__(self, tup):
        self.name, self.surname, self.int1, self.int2 = tup
    def __lt__(self, other):
        # Just to make the logic clearer, in practise you could do nest the ifs
        # to avoid computing self.int1 == other.int1 twice
        if self.int1 == other.int1 and self.name == other.name:
            return self.surname < other.surname
        elif self.int1 == other.int1:
            return self.name > other.name
        else:
            return self.int1 > other.int1

然后将其用作key for sorted

>>> sorted(a, key=Sorter)
[('Yana', 'Anja', 10, 0),
 ('Kolia', 'Alexey', 10, 0),
 ('Vasia', 'Katia', 3, 0),
 ('Petia', 'Anja', 3, 0),
 ('Petia', 'Katia', 3, 0)]

【讨论】:

    【解决方案2】:
    >>> intab='abcdefghijklmnopqrstuvwxyz'
    >>> tab = string.maketrans(intab+intab.upper(), intab[::-1]+intab.upper()[::-1])
    >>> 
    >>> slst = sorted(lst, key = lambda x: [-int(x[2]), x[0].translate(tab), x[1]])
    >>> pprint(slst)
    [('Yana', 'Anja', 10, 0),
     ('Kolia', 'Alexey', 10, 0),
     ('Vasia', 'Katia', 3, 0),
     ('Petia', 'Anja', 3, 0),
     ('Petia', 'Katia', 3, 0)]
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 2017-10-04
      相关资源
      最近更新 更多