Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将整数列表转换为字符串作为排序中dict的键_Python_Sorting_Dictionary - Fatal编程技术网

Python 将整数列表转换为字符串作为排序中dict的键

Python 将整数列表转换为字符串作为排序中dict的键,python,sorting,dictionary,Python,Sorting,Dictionary,我有一个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) 我想要的是L1是[1,0,2,3,4] 显然,排序行不起作用,因为数字不是dict的正确键 我已经有了节点,

我有一个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)
我想要的是L1是
[1,0,2,3,4]

显然,排序行不起作用,因为数字不是dict的正确键

我已经有了节点,所以我的想法是将L1转换成字符串值,使用结果字符串作为排序的键,但我不知道怎么做

我可以在某种形式的超级循环中实现这一点,但我正在尝试学习python,我相信有一种更类似python的方法来实现这一点。

您可以编写一个lambda表达式作为密钥:

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

l1.sort(key=(lambda x,d=nodes:d[str(x)])
list(map(names.get,sorted)(map(nodes.get,map(str,l1'))))
这样做是错误的。StevenRumbalski您的lambda与@Psidom接受的答案略有不同。你认为哪种形式更好吗?正如你所知,整数可以作为dict键。。。如果您有
nodes={0:b',1:a'…}
,那么
l1.sort(key=nodes.get)
可以正常工作!非常感谢。我得让我的lambda跑得更好。我试过了,但没把它调好。