繁体   English   中英

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

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

我有一个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] 1,0,2,3,4 [1, 0, 2, 3, 4]

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

我有节点,所以我的想法是将L1转换为字符串值,使用结果字符串作为排序的键,但我只是不知道如何做到这一点。

我可以在某种巨型循环中做到这一点,但我正在尝试学习python,我确信有更多的pythonic方法来做到这一点。

您可以将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