简体   繁体   English

蟒蛇。 通过分割字符串键对字典排序

[英]Python. Sort list of dicts by splitting string key

I have a list of dicts like this: 我有这样的字典列表:

my_list=[{'c': '1/2014'},
{'c': '1/2015'},
{'c': '10/2014'},
{'c': '2/2014'},
{'c': '3/2014'},
{'c': '1/2011'},
{'c': '2/2011'},
{'c': '3/2011'},
{'c': '6/2014'},
{'c': '5/2014'},
{'c': '10/2014'},
{'c': '2/2015'},
{'c': '4/2015'},
{'c': '3/2015'},
{'c': '5/2016'},
{'c': '1/2017'}]

I want order my list by the c key. 我想按C键订购我的清单。 The key have two parts: year_counter / year, so first I have to order by year and then by year_counter, inside each year gruop. 关键有两个部分:year_counter / year,所以首先我必须按年排序,然后按year_counter在每年的组中排序。 At the end I expect to have this: 最后,我希望有:

my_list=[{'c': '1/2011'},
 {'c': '2/2011'},
 {'c': '3/2011'},
 {'c': '1/2014'},
 {'c': '2/2014'},
 {'c': '3/2014'},
 {'c': '5/2014'},
 {'c': '6/2014'},
 {'c': '10/2014'},
 {'c': '1/2015'},
 {'c': '2/2015'},
 {'c': '3/2015'},
 {'c': '4/2015'},
 {'c': '11/2015'},
 {'c': '5/2016'},
 {'c': '1/2017'}]

What is the best efficent way to achieve this? 实现这一目标的最佳方法是什么?

I think idea should be to split this month and year first then apply some sorting algorithm to sort it. 我认为思路应该是这个分裂monthyear第一再涂抹一些排序算法来排序。

you can use the underscore library for that. 您可以使用underscore库。 notice my fiddle 注意我的fiddle

https://jsfiddle.net/stdeepak22/96trt0r4/1/ https://jsfiddle.net/stdeepak22/96trt0r4/1/

first I splitted your value of c to month and year. 首先,我将您的c值拆分为月份和年份。

var split_list = _.map(my_list, function(r){
    return {
      mn : parseInt(r.c.split('/')[0]),
      yr : parseInt(r.c.split('/')[1])
    };
  }); 

then I apply sorting then again joining back to actual field c value 然后我应用排序,然后再次加入实际的字段c

var sorted_list= _.chain(split_list)
  .sortBy(function(f)
  {
    return f.mn;
  }).sortBy(function(f)
  {
    return f.yr;
  }).map(function(obj)
  {
    return { c: obj.mn+'/'+obj.yr }
  }).value();

then I printed on console to check the output. 然后我在控制台上打印以检查输出。

console.log(sorted_list);

Initially I forgot to parse the month and year value to int. 最初,我忘记将月份和年份值解析为int。 that I have corrected now. 我现在已经纠正了。

UPDATE Initially you didn't tag, Python I thought you are looking for json, so I provided the JavaScript solution. 更新最初,您没有标记Python,我以为您正在寻找json,所以我提供了JavaScript解决方案。

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

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