tij*_*jko 11 python sorting dictionary list
说我有一本字典然后我有一个包含字典键的列表.有没有办法根据字典值对列表进行排序?
我一直在尝试这个:
trial_dict = {'*':4, '-':2, '+':3, '/':5}
trial_list = ['-','-','+','/','+','-','*']
Run Code Online (Sandbox Code Playgroud)
我去用了:
sorted(trial_list, key=trial_dict.values())
Run Code Online (Sandbox Code Playgroud)
得到了:
TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)
然后我去创建一个可以调用的函数trial_dict.get():
def sort_help(x):
if isinstance(x, dict):
for i in x:
return x[i]
sorted(trial_list, key=trial_dict.get(sort_help(trial_dict)))
Run Code Online (Sandbox Code Playgroud)
我不认为该sort_help功能对排序有任何影响.我不确定使用trial_dict.get()是否也是正确的方法.
geo*_*org 13
是的dict.get是正确的(或至少是最简单的)方式:
sorted(trial_list, key=trial_dict.get)
Run Code Online (Sandbox Code Playgroud)
正如Mark Amery评论的那样,等效的显式lambda:
sorted(trial_list, key=lambda x: trial_dict[x])
Run Code Online (Sandbox Code Playgroud)
可能会更好,至少有两个原因:
sorted内置函数(或sort列表方法)中的关键参数必须是一个函数,用于将要排序的列表成员映射到要排序的值.所以你想要这个:
sorted(trial_list, key=lambda x: trial_dict[x])
Run Code Online (Sandbox Code Playgroud)