【问题标题】:Sort list of lists first by year, then by month [duplicate]首先按年对列表进行排序,然后按月[重复]
【发布时间】:2018-05-30 22:22:11
【问题描述】:

我有一个看起来像这样的列表:

dateList = [['2014', '4'], ['2015', '6'], ['2017', '6'], ['2016', '2'], ['2016', '3'], ['2017', '9'], ['2016', '6'], ['2017', '3'], ['2014', '8'], ['2014', '10'], ['2017', '10'], ['2014', '9'], ['2014', '3'], ['2015', '11'], ['2015', '2']]

我一直在尝试先按年排序,然后按月排序。我已经成功地使用了

sortedList = sorted(dateList, key = lambda x: int(x[0]))

但是,我想不出一种方法来按月排序,同时保持年份升序。

【问题讨论】:

  • 尝试传递一个元组
  • @jonrsharpe:如果没有 int,那么几个月内 10 会出现在 9 之前。
  • @fuglede 好点,但是只有需要转换月份,OP 的当前代码没有任何好处。

标签: python python-3.x list sorting


【解决方案1】:

传递一个元组:

sorted(dateList, key = lambda x: (int(x[0]),int(x[1])))

但这看起来更好:

sorted(dateList, key = lambda x: tuple(map(int,x)))

另一种选择是使用:

import datetime 
sorted(dateList, key = lambda x: datetime.datetime.strptime(''.join(x),'%Y%m'))

【讨论】:

  • 谢谢,我使用了第一个,因为它更符合我的代码并且似乎更符合 Python 风格。
  • 不客气。第二个更pythonic。
【解决方案2】:

您似乎需要对数据进行自然排序。您可以使用 natsort 包来执行此操作,而无需传递任何密钥 -

import natsort

natsort.natsorted(dateList)

[['2014', '3'],
 ['2014', '4'],
 ['2014', '8'],
 ['2014', '9'],
 ['2014', '10'],
 ['2015', '2'],
 ['2015', '6'],
 ['2015', '11'],
 ['2016', '2'],
 ['2016', '3'],
 ['2016', '6'],
 ['2017', '3'],
 ['2017', '6'],
 ['2017', '9'],
 ['2017', '10']]

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2011-02-17
    • 1970-01-01
    • 2014-09-22
    • 2013-02-12
    • 1970-01-01
    • 2023-03-05
    • 2023-03-25
    • 2023-03-13
    相关资源
    最近更新 更多