2

I was trying to sort the following list :

L = ['Z3', 'X3','V3','M0' ..., 'F2'] 

Based on the rules, I defined in the 2 following dictionaries:

dicMonths = {'F':1,'G':2,'H':3,'J':4,'K':5,'M':6,'N':7,'Q':8,'U':9,'V':10,'X':11,'Z':12}
dicYears = {'2':2022, '1':2021, '0':2020, '9':2019, '8':2018, '7':2017, '6':2016, '5':2015, '4':2014, '3':2013}

I applied the following code, but it doesn't work :

aa = [(elt[0], elt[1]) for elt in L]
sorted(aa, key= lambda x,y : (dicMonths[x], dicYears[y]))

It gives me the following error :

TypeError: () missing 1 required positional argument: 'y'

I want it to give me the sorted list as bellow :

['F3', 'G3', 'H3', 'J3', 'K3', 'M3', 'N3', 'Q3', 'U3', 'V3', 'X3', 'Z3', 'F4', ...]

How can I resolve this problem?

Khadija
  • 72
  • 1
  • 8

2 Answers2

0

You provided an incompatible function for the key argument. key takes a function that accepts one argument and returns another. If you want this to work, you need to access the tuple argument as a single value.

Also, you don't need to split L as a separate step. Try this:

sorted(L, key=lambda l: (dicMonths[l[0]], dicYears[l[1]]))
flakes
  • 21,558
  • 8
  • 41
  • 88
0

The suggestion from @flakes is very elegant, but probably does not produce the required output, because it gives month precedence over years. However, according to the desired output mentioned in the question, years should have precedence over months - e.g. 'Z3' < 'F4'.

That can be achieved with a slight adaption:

sorted(L, key=lambda l: (dicYears[l[1]], dicMonths[l[0]]))
buertho
  • 16
  • 1
  • yes, you're right I recognized it when he posted the suggestion but forgot to mention it in the comment, thanks – Khadija Sep 24 '21 at 16:34