什么是最Python的方式,以日期顺序排序? [英] What is the most pythonic way to sort dates sequences?

查看:109
本文介绍了什么是最Python的方式,以日期顺序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有刺的列表重新$ P $一年psenting一个月(不排序,而不是连续的): ['二千○十三分之一','二千零一十三分之七','二千○十三分之二','二千〇一十三分之三','二千零十四分之四','12 / 2013','10 / 2013,二千〇十三分之一十一','二千〇一十四分之一','二千○一十四分之二']

I have a list of stings representing a month in a year (not sorted and not consecutive): ['1/2013', '7/2013', '2/2013', '3/2013', '4/2014', '12/2013', '10/2013', '11/2013', '1/2014', '2/2014']

我在找一个Python化的方式进行排序所有这些,分隔每个连续的序列如下建议:

I'm looking for a Pythonic way to sort all of them and separate each consecutive sequence as the following suggests:

[ ['1/2013', '2/2013', '3/2013', '4/2013'], 
  ['7/2013'], 
  ['10/2013', '11/2013', '12/2013', '1/2014', '2/2014'] 
]

任何想法?

推荐答案

根据从演示了如何找到连续数字的运行使用的 itertools.groupby()

Based on the example from the docs that shows how to find runs of consecutive numbers using itertools.groupby():

from itertools import groupby
from pprint import pprint

def month_number(date):
    month, year = date.split('/')
    return int(year) * 12 + int(month)

L = [[date for _, date in run]
     for _, run in groupby(enumerate(sorted(months, key=month_number)),
                           key=lambda (i, date): (i - month_number(date)))]
pprint(L)

的关键解决方案是差分与产生了一系列枚举(),这样连续几个月都出现在同一个组(运行)。

The key to the solution is differencing with a range generated by enumerate() so that consecutive months all appear in same group (run).

[['1/2013', '2/2013', '3/2013'],
 ['7/2013'],
 ['10/2013', '11/2013', '12/2013', '1/2014', '2/2014'],
 ['4/2014']]

这篇关于什么是最Python的方式,以日期顺序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆