我看到这种方法可以根据dict值将列表排序为键。
我们可以使用此方法根据每个列表中的第一个值对列表列表进行排序吗?
trial_dict = {1:'ABC', 2:'PQR', 3:'DEF'}
trial_list = [['ABC','-','+','/','+','-','*'],
['DEF','-','+','/','+','-','*'],
['PQR','-','+','/','+','-','*']]
排序后:
trial_list = [['ABC','-','+','/','+','-','*'],
['PQR','-','+','/','+','-','*'],
['DEF','-','+','/','+','-','*']]
答案 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',' - ','+','/','+',' - ','*']]