简体   繁体   English

一种使用字典对列表中的整数进行排序的方法

[英]A way to sort integers in a list by using a dictionary

I was wondering if there would be a way to sort a list in order according to the increasing floats as values in a dictionary. 我想知道是否有一种方法可以根据不断增加的浮点数在字典中按值对列表进行排序。 I don't really know how to explain it so I'll demonstrate what I mean 我真的不知道该怎么解释,所以我会证明我的意思

[3, 6, 4]

to

[6, 4, 3]

with dictionary like this 用这样的字典

{6: 15.6, 3: 120.0, 4: 17.3}

Use the key argument of sorted : 使用key的参数排序

>>> mylist = [3, 6, 4]
>>> mydict = {6:15.6, 3:120.0, 4:17.3}
>>> sorted(mylist, key=mydict.get)
[6, 4, 3]

For your example, you don't even need that list as the dict keys are sufficient: 对于您的示例,您甚至不需要该列表,因为dict键就足够了:

>>> my_dict = {6: 15.6, 3: 120.0, 4: 17.3}
>>> sorted(my_dict, key=my_dict.get)
[6, 4, 3]

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

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