将 python 月份列表映射到值
map python list of months to values
我有 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 如何将列表按月排序,同时保留现有的值到月的映射?
想法是
- 关联两个列表
- 根据year/month标准对结果列表排序(必须先使用辅助字典将月份转换为月份索引)
- 然后将情侣列表分成 2 个列表,但现在根据日期排序。
这是一个注释代码,它可以满足您的需求,可能不是最紧凑或最学术的代码,但可以工作并且足够简单。
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]
我有 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 如何将列表按月排序,同时保留现有的值到月的映射?
想法是
- 关联两个列表
- 根据year/month标准对结果列表排序(必须先使用辅助字典将月份转换为月份索引)
- 然后将情侣列表分成 2 个列表,但现在根据日期排序。
这是一个注释代码,它可以满足您的需求,可能不是最紧凑或最学术的代码,但可以工作并且足够简单。
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]