简体   繁体   中英

Python. Sort 2D list based on two keys and a dict

I'm trying to resolve this exercise. I have a dict with a code:order.

codes = {'JA':0,'FE':1,'MA':2,'AP':3,'MY':4,'JU':5,'JL':6,'AG':7,'SE':8,'OC':9,'NO':10,'DI':11}

and a sample od data:

sample = [['NO15',27],['JU17',45],['FE18',-4],['AP14',7],['JA18',97]]

and I want to sort the sample under two criteria. First, the year, thats it, the two digits that accompany the code of the month, and secoond, the order of the month in the dictionary The result must be:

sorted_sample = [['AP14',7],['NO15,27],['JU17',45],['JA18',97],['FE18',-4]]

I'm trying it with this

sorted(raw, key=lambda x: (x[2:4],codes.get(x[0][:2])))

sorted(sorted(raw, key = lambda x : x[2:4], reverse = True), key = lambda x : codes.get(x[0][:2]), reverse = False)

but I do not get the right result.

You can try this:

import re
codes = {'JA':0,'FE':1,'MA':2,'AP':3,'MY':4,'JU':5,'JL':6,'AG':7,'SE':8,'OC':9,'NO':10,'DI':11}
sample = [['NO15',27],['JU17',45],['FE18',-4],['AP14',7],['JA18',97]]
final_sample = sorted(sample, key=lambda x: (int(re.findall('\d+$', x[0])[0]), codes[re.findall('^[a-zA-Z]+', x[0])[0]], x[-1]))

Output:

[['AP14', 7], ['NO15', 27], ['JU17', 45], ['JA18', 97], ['FE18', -4]]

You need to index into the list to get the year. Also, convert it to int so that it compares as number:

>>> sorted(sample, key=lambda x: (int(x[0][2:4]), codes.get(x[0][:2])))
[['AP14', 7], ['NO15', 27], ['JU17', 45], ['JA18', 97], ['FE18', -4]]

Thanks to both of you. I found the mistake in the code. I was trying to cast the elements of the sample to integer after the [2:4]. I forget to choose the first part only. int(x[0][2:4]) instead of int(x[2:4]).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM