简体   繁体   English

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

[英]Sort list of lists based on a dict values as key

I saw this method to sort list based on dict values as key. 我看到了这种基于dict值作为键对列表进行排序的方法。

Original Question here 原始问题在这里

Can we use this method to sort list of lists based on first value in each list? 我们可以使用此方法根据每个列表中的第一个值对列表列表进行排序吗?

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

After sorting: 排序后:

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

You can use sorted() function. 您可以使用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]])

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM