Sort months ( with strings ) algorithm

前端 未结 10 1162
深忆病人
深忆病人 2021-01-18 03:42

I have this months array:

[\"January\", \"March\", \"December\" , \"October\" ]

And I want to have it sorted like this:

[\"         


        
10条回答
  •  不知归路
    2021-01-18 04:29

    Create a mapping:

    month_map = {"January":1,
                 "February":2,
                 "March":3,
                 "April":4} # etc..
    

    Use the mapping to compare one month to the other.

    OR

    Most languages/frameworks have objects for handling dates. Create date objects for all the months and compare them using the native (if available) inequality operators or basic sorting functions:

    import datetime
    January  = datetime.date(2010,1,1)
    February = datetime.date(2010,2,1)
    if February < January: print("The world explodes.")
    

提交回复
热议问题