我有2个列表,其中第二个列表中的值序列映射到第一个列表中的月份:
['Apr-16', 'Jul-16', 'Dec-15', 'Sep-16', 'Aug-16', 'Feb-16', 'Mar-16', 'Jan-16', 'May-16', 'Jun-16', 'Oct-15', 'Nov-15']
[15, 15, 6, 81, 60, 36, 6, 18, 36, 27, 24, 29]
我需要保留2个单独的列表以用于其他功能。使用python如何实现按月顺序对列表进行排序,同时保留现有的值映射到几个月?
答案 0 :(得分:1)
想法是
这是一个评论代码,它可以满足您的需求,也许不是最紧凑或最具学术性的,但也很简单。
a = ['Apr-16', 'Jul-16', 'Dec-15', 'Sep-16', 'Aug-16', 'Feb-16', 'Mar-16', 'Jan-16', 'May-16', 'Jun-16', 'Oct-15', 'Nov-15']
b = [15, 15, 6, 81, 60, 36, 6, 18, 36, 27, 24, 29]
# create a dictionary key=month, value=month index
m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
monthdict = dict(zip(m,range(len(m))))
# the sort function: returns sort key as (year as integer,month index)
def date_sort(d):
month,year = d[0].split("-")
return int(year),monthdict[month]
# zip both lists together and apply sort
t = sorted(zip(a,b),key=date_sort)
# unzip lists
asort = [e[0] for e in t]
bsort = [e[1] for e in t]
print(asort)
print(bsort)
结果:
['Oct-15', 'Nov-15', 'Dec-15', 'Jan-16', 'Feb-16', 'Mar-16', 'Apr-16', 'May-16', 'Jun-16', 'Jul-16', 'Aug-16', 'Sep-16']
[24, 29, 6, 18, 36, 6, 15, 36, 27, 15, 60, 81]