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?
CodePudding user response:
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]]))