简体   繁体   English

蟒蛇。 根据两个键和一个字典对2D列表进行排序

[英]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. 我有一个带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: 以及示例od数据:

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: 另外,将其转换为int以便与数字进行比较:

>>> 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]. 我试图将[2:4]之后的样本元素转换为整数。 I forget to choose the first part only. 我忘了只选择第一部分。 int(x[0][2:4]) instead of int(x[2:4]). int(x [0] [2:4])而不是int(x [2:4])。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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