使用字典对列表进行排序

时间:2017-03-13 20:18:34

标签: python sorting

我有以下数据列表:

[['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 个答案:

答案 0 :(得分:0)

您忘记在字典中映射tes,将'tes':13添加到index_sort并且它可以正常工作!

答案 1 :(得分: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}