2017-03-13 69 views
-1

名單我有一個下面的列表數據:排序使用字典

[['0', 'r1', 0.02, '-115.047611580259'], ['-', 'r1', 0.02, '-115.047523465090'], ['+', 'r1', 0.02, '-115.047530021958'], ['-', 'r2', 0.02, '-115.047482517212'], ['+', 'r2', 0.02, '-115.047488665041'], ['-', 'r3', 0.02, '-115.047537136035'], ['+', 'r3', 0.02, '-115.047540343182'], ['-', 'r4', 0.02, '-115.047536709065'], ['+', 'r4', 0.02, '-115.047539744629'], ['-', 'r5', 0.02, '-115.047536709065'], ['+', 'r5', 0.02, '-115.047539744630'], ['-', 'T1', 0.017453292519943295, '-115.047582049644'], ['+', 'T1', 0.017453292519943295, '-115.047580299567'], ['-', 'T2', 0.017453292519943295, '-115.047565855131'], ['+', 'T2', 0.017453292519943295, '-115.047566778954'], ['-', 'T3', 0.017453292519943295, '-115.047566430596'], ['+', 'T3', 0.017453292519943295, '-115.047566580788'], ['-', 'T4', 0.017453292519943295, '-115.047566430596'], ['+', 'T4', 0.017453292519943295, '-115.047566580788'], ['-', 'T5', 0.017453292519943295, '-115.047582679863'], ['+', 'T5', 0.017453292519943295, '-115.047582679863'], ['-', 'T6', 0.017453292519943295, '-115.047581038699'], ['+', 'T6', 0.017453292519943295, '-115.047580181415'], ['-', 'T7', 0.017453292519943295, '-115.047580181415'], ['+', 'T7', 0.017453292519943295, '-115.047581038699'], ['t', 'tes', 0.017453292519943295, '-115.047611580259']] 

我想值進行排序,所以我創建詞典:

index_sort = {'r1':1, 'r2':2, 'T1':3, 'r3':4, 'T2':5, 'T3':6, 'r4':7, 'T4':8, 'T5':9, 'r5':10, 'T6':11, 'T7':12} 
Eall_sorted = sorted(Eall, key = lambda e: index_sort[e[1]]) 

的問題是,我得到回報錯誤:

Eall_sorted = sorted(Eall, key = lambda e: index_sort[e[1]]) 
KeyError: 'tes' 

有沒有人可以詳細說明我的代碼出了什麼問題?

+2

你離開'tes'了'index_sort'的更換。 –

+0

這完全有道理。我沒有注意到它。非常感謝! – Monica

回答

0

您忘記了地圖tes在字典中,將'tes':13添加到index_sort,它的工作原理!

0

在這一行

index_sort = {'r1':1, 'r2':2, 'T1':3, 'r3':4, 'T2':5, 'T3':6, 'r4':7, 'T4':8, 'T5':9, 'r5':10, 'T6':11, 'T7':12} 

你忘了添加 'TES'。

您可以

index_sort = {'r1':1, 'r2':2, 'T1':3, 'r3':4, 'T2':5, 'T3':6, 'r4':7, 'T4':8, 'T5':9, 'r5':10, 'T6':11, 'T7':12, 'tes':13}