繁体   English   中英

使用字典键值对列表进行排序

[英]Sort list using dictionary key values

可以说我有一个清单

list_values = ['key3', 'key0', 'key1', 'key4', 'key2']

和命令的命令

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

如何使用ordered_dict键对list_values进行排序?

即: sorted_list = ['key4', 'key1', 'key2', 'key0', 'key3']

编辑:由于几乎所有的答案都可以解决问题,什么是最合适,最完美的pythonic方法?

调用list.sort ,传递一个自定义key

list_values.sort(key=ordered_dict.get)    
list_values
# ['key4', 'key1', 'key2', 'key0', 'key3']

另外,非就地版本也可以使用

sorted(list_values, key=ordered_dict.get)
# ['key4', 'key1', 'key2', 'key0', 'key3']

如果我们假设列表是dict的子集:

list_values = ['key3', 'key1']

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

output = [v for v in ordered_dict if v in list_values]

print(output)

['key1', 'key3']

范例2:

list_values = ['key3', 'key0', 'key1', 'key4', 'key2']

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

output = [v for v in ordered_dict if v in list_values]

print(output)

['key4', 'key1', 'key2', 'key0', 'key3']

暂无
暂无

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

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