基于dict值作为键对列表列表进行排序

时间:2016-06-02 11:12:47

标签: python list sorting dictionary

我看到这种方法可以根据dict值将列表排序为键。

Original Question here

我们可以使用此方法根据每个列表中的第一个值对列表列表进行排序吗?

trial_dict = {1:'ABC', 2:'PQR', 3:'DEF'}
trial_list = [['ABC','-','+','/','+','-','*'],
              ['DEF','-','+','/','+','-','*'],
              ['PQR','-','+','/','+','-','*']]

排序后:

trial_list = [['ABC','-','+','/','+','-','*'],
              ['PQR','-','+','/','+','-','*'],
              ['DEF','-','+','/','+','-','*']]

1 个答案:

答案 0 :(得分:1)

您可以使用sorted()功能。

trial_dict = {1:'ABC', 2:'PQR', 3:'DEF'}
trial_dict_inv = {v: k for k, v in trial_dict.items()}
trial_list = [['ABC','-','+','/','+','-','*'],
          ['DEF','-','+','/','+','-','*'],
          ['PQR','-','+','/','+','-','*']]


print sorted(trial_list, key= lambda z:trial_dict_inv[z[0]])

输出:

  

[['ABC',' - ','+','/','+',' - ','*'],   ['PQR',' - ','+','/','+',' - ','*'],   ['DEF',' - ','+','/','+',' - ','*']]