2017-04-12 59 views
1

的一天,我有一個數組是這樣的:Python的排序多維數組一樣

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

您可以創建平日列表排序,然後排序的鍵列表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],['Wed',27],['Thu',40] ,[ '星期五',69],[ '星期六',78],[ '太陽',90]]

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)] 
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」)並獲取映射中對應的數字。