什么是最Python的方式,以日期顺序排序?顺序、日期、方式、Python

2023-09-11 05:45:45 作者:草编の戒指

我有刺的列表重新$ 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']]