How to sort one list of lists using a custom conditional?

Viewed 52

I have a list of lists of a bank account in which two operations are registered, deposit and withdraw money.

Each list inside the list has the format [date_of_operation, amount, balance] where a positive amount means "deposit operation" and negative amount means "withdraw operation"

Example:

# date       || amount  || balance
# 01/01/2001 || -200.00 || 300.76
# 20/10/1992 || 500.76  || 500.76
# 13/07/2021 || 1000.00 || 1300.76
# 13/07/2021 || -200.00 || 1100.76


account = [
        [datetime.strptime("01/01/2001", "%d/%m/%Y"), -200.0, 300.76],
        [datetime.strptime("20/10/1992", "%d/%m/%Y"), 500.76, 500.76], 
        [datetime.strptime("13/07/2021", "%d/%m/%Y"), 1000.0, 1300.76], 
        [datetime.strptime("13/07/2021", "%d/%m/%Y"), -200, 1100.76]
]

Now I want to sort the list with two conditions:

  1. By date in reverse order
  2. If the date between two items is the same, the balance has to follow a coherent order

Example of the desired input:

date       || amount  || balance
13/07/2021 || -200.00 || 1100.76
13/07/2021 || 1000.00 || 1300.76
01/01/2001 || -200.00 || 300.76
20/10/1992 || 500.76  || 500.76

But I can not acomplish this, what I tried is to sort the list by date and balance in reverse order:

account = sorted(account, key=lambda x:(x[0], x[2]), reverse=True)

But the output is not what want because the first two items are interchanged:

date       || amount  || balance
13/07/2021 || 1000.00 || 1300.76
13/07/2021 || -200.00 || 1100.76
01/01/2001 || -200.00 || 300.76
20/10/1992 || 500.76  || 500.76

How could I get the desired output using a custom condition in sorted function?

1 Answers

The easiest fix is to negate the balance component in the sort key:

ount = sorted(account, key=lambda x:(x[0], -x[2]), reverse=True)

That will effectively undo the effect of reverse on the balance, while leaving the date portion unaffected.

Related