我有一个这样的数组:
a=[["Wed", 27], ["Sun", 90], ["Fri", 69], ["Tue", 47], ["Mon", 54], ["Thu", 40], ["Sat", 78]];
我想通过python 2.7将数组排序为星期几。像这样;
[["Mon", 54], ["Tue", 47], ["Wed", 27], ["Thu", 40], ["Fri", 69], ["Sat", 78], ["Sun", 90]]
...谢谢
答案 0 :(得分:0)
您可以创建一个映射,然后按此排序。
import operator as op
mapping = {'Mon':0,'Tue':1,'Wed':2,'Thu':3,'Fri':4,'Sat':5,'Sun':6}
orig_list = [["Wed", 27], ["Sun", 90], ["Fri", 69], ["Tue", 47],
["Mon", 54], ["Thu", 40], ["Sat", 78]]
new_list = zip(orig_list,[mapping[i[0]] for i in orig_list])
new_list.sort(key=op.itemgetter(1))
收率:
>>> new_list
[(['Mon', 54], 0), (['Tue', 47], 1), (['Wed', 27], 2), (['Thu', 40], 3),
(['Fri', 69], 4), (['Sat', 78], 5), (['Sun', 90], 6)]
答案 1 :(得分:0)
您可以创建一个按工作日排序的列表,然后按其键对列表a
进行排序:
>>> a = [["Wed", 27], ["Sun", 90], ["Fri", 69], ["Tue", 47], ["Mon", 54], ["Thu", 40], ["Sat", 78]]
>>> order = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
>>> sorted(a, key=lambda x: order.index(x[0]))
输出将是:
[[' Mon',54],[' Tue',47],['周三',27],['周四&# 39;,40],[' Fri',69],[' Sat',78],[' Sun',90]]
答案 2 :(得分:0)
您可以在值和数字之间定义映射,而无需使用任何导入。
a = [["Wed", 27], ["Sun", 90], ["Fri", 69], ["Tue", 47], ["Mon", 54], ["Thu", 40], ["Sat", 78]]
mapping = {
"Mon": 1,
"Tue": 2,
"Wed": 3,
"Thu": 4,
"Fri": 5,
"Sat": 6,
"Sun": 7
}
a.sort(key = lambda x: mapping[x[0]])
print(a)
在此指定您要使用匿名函数对列表进行排序。此匿名函数将提取字符串(例如“Sun”)并获取映射中对应的数字。