基于日期部分反转的 Python 列表排序列表

Ale*_*yuk 5 python sorting datetime

我有个问题。我有一个看起来像这样的列表:

[
[datetime.date(2019, 3, 29), Decimal('44819.75')],
[datetime.date(2019, 3, 29), Decimal('45000.00')],
[datetime.date(2019, 3, 28), Decimal('0.00')],
[datetime.date(2019, 3, 22), Decimal('-275.00')],
[datetime.date(2019, 3, 22), Decimal('-350.00')],
[datetime.date(2019, 3, 22), Decimal('-175.00')]
]
Run Code Online (Sandbox Code Playgroud)

我需要在日期字段(第一个)上进行排序,但每组相同的日期必须以相反的顺序排序。结果列表必须如下所示:

[
[datetime.date(2019, 3, 29), Decimal('45000.00')],
[datetime.date(2019, 3, 29), Decimal('44819.75')],
[datetime.date(2019, 3, 28), Decimal('0.00')],
[datetime.date(2019, 3, 22), Decimal('-175.00')],
[datetime.date(2019, 3, 22), Decimal('-350.00')],
[datetime.date(2019, 3, 22), Decimal('-275.00')],
]
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,列表是按日期排序的,但是对于相同的日期,列表是相反的。

日期仍在下降 2019-3-29 2019-3-28 2019-3-22 但对于每个日期,如果该日期有 1 个以上的元素,则项目会颠倒。

2019-3-29 有 2 个元素

[datetime.date(2019, 3, 29), Decimal('44819.75')],
[datetime.date(2019, 3, 29), Decimal('45000.00')],
Run Code Online (Sandbox Code Playgroud)

并在结果列表中的列表顺序颠倒

[datetime.date(2019, 3, 29), Decimal('45000.00')],
[datetime.date(2019, 3, 29), Decimal('44819.75')],

Run Code Online (Sandbox Code Playgroud)

不幸的是,我找不到最pythonic的方法来做到这一点,只有丑陋的嵌套循环

Ale*_*lon 2

我冒昧地简化了数据类型,因为这样更容易阅读。

# Simplified representation.
# a few random values at the start and then multiple 2's and that the current order is a,b,c
# We expect all values to be sorted on the integer part first. And that the order for the 2's is c,b,a at the end.
data = [
    [1, '-'],
    [5, '-'],
    [3, '-'],

    [2, 'a'],
    [2, 'b'],
    [2, 'c']
]


data = data[::-1]
data = sorted(data, key=lambda x:x[0])
Run Code Online (Sandbox Code Playgroud)

打印数据将产生:

[1, '-']
[2, 'c']
[2, 'b']
[2, 'a']
[3, '-']
[5, '-']
Run Code Online (Sandbox Code Playgroud)

我相信这就是你想要的。

该解决方案非常易于阅读,在与他人合作时有其好处。

sorted在python中是一种稳定的排序算法。这就是为什么如果正常排序,“ab c”的顺序会被保留。这就是为什么首先反转起作用,排序不会改变相同项目出现的顺序。

请注意,这也有效。

data = sorted(data, key=lambda x:x[0], reverse=True)
data = data[::-1]
Run Code Online (Sandbox Code Playgroud)

这里我们进行反向排序,然后向后读取数据。