【问题标题】:Python. Sort 2D list based on two keys and a dictPython。基于两个键和一个字典对二维列表进行排序
【发布时间】:2017-12-19 15:11:32
【问题描述】:

我正在尝试解决这个问题。 我有一个带有代码的字典:订单。

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}

还有一个样本 od 数据:

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

我想根据两个标准对样本进行排序。第一,年份,就是月份代码的两位数字,第二,字典中月份的顺序 结果必须是:

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

我正在尝试这个

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)

但我没有得到正确的结果。

【问题讨论】:

    标签: python list sorting dictionary key


    【解决方案1】:

    您需要索引到列表中才能获得年份。另外,将其转换为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]]
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      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]))
      

      输出:

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

      【讨论】:

        【解决方案3】:

        感谢你们俩。我在代码中发现了错误。我试图在 [2:4] 之后将样本的元素转换为整数。我忘记只选择第一部分。 int(x[0][2:4]) 而不是 int(x[2:4])。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-04
          • 1970-01-01
          • 2020-12-04
          • 2014-09-21
          • 2015-05-02
          • 2016-08-03
          • 2013-11-02
          相关资源
          最近更新 更多