简体   繁体   English

将int的列表转换为字符串作为sort中dict的键

[英]Convert list of ints to strings as key for dict in sort

I have a dict that I want to use as the key for sorting a list. 我有一个dict,我想用它作为排序列表的关键。

names = {'a': 1,  'b': 0, 'c': 2, 'd': 3, 'e': 4, 'f': 5,}
nodes = {'0': 'b', '1': 'a', '2': 'c', '3': 'd', '4': 'e', '5': 'f'}

l1 = [0, 1, 2, 3, 4]
l1.sort(key=names.get)

What I want is L1 to be [1, 0, 2, 3, 4] . 我想要的是L1 [1, 0, 2, 3, 4] 1,0,2,3,4 [1, 0, 2, 3, 4]

Obviously the sort line doesn't work as the numbers aren't proper keys for the dict. 显然排序行不起作用,因为数字不是dict的正确键。

I've got the nodes, so my thought is to convert L1 into string values, use the resulting string as the key for the sort, but I just don't know how to do that. 我有节点,所以我的想法是将L1转换为字符串值,使用结果字符串作为排序的键,但我只是不知道如何做到这一点。

I could do this in some sort of mega loop, but i'm trying to learn python and i'm sure there is a more pythonic way to do it. 我可以在某种巨型循环中做到这一点,但我正在尝试学习python,我确信有更多的pythonic方法来做到这一点。

You can write a lambda expression as key: 您可以将lambda表达式写为键:

l1.sort(key=lambda x: nodes.get(str(x)))         # convert the int to str here
l1
# [1, 0, 2, 3, 4]

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

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