简体   繁体   English

Python,当键是科学格式的浮点数时,如何按键对字典进行排序?

[英]Python, how to sort dictionary by keys, when keys are floating point numbers in scientific format?

I need to sort a Python dictionary by keys, when keys are floating point numbers in scientific format. 当键是科学格式的浮点数时,我需要按键对Python字典进行排序。

Example: 例:

a={'1.12e+3':1,'1.10e+3':5,'1.19e+3':7,...}

I need to maintain key-value links unchanged. 我需要保持键值链接不变。
What is the simplest way to do this? 最简单的方法是什么?

Probably by simply converting back to a number: 可能只需转换回一个数字:

sorted(a, key = lambda x: float(x))
['1.10e+3', '1.12e+3', '1.19e+3']

This just gives you a sorted copy of the keys. 这只是给你一个键的排序副本。 I'm not sure if you can write to a dictionary and change its list of keys (the list returned by keys() on the dictionary) in-place. 我不确定你是否可以写入字典并在其中更改其键列表keys()字典上的keys()返回的列表)。 Sounds a bit evil. 听起来有点邪恶。

You can sort the (key, value) pairs by the float value 您可以按浮点值对(key, value)对进行排序

a={'1.12e+3':1,'1.10e+3':5,'1.19e+3':7,...}
print sorted(a.iteritems(), key=lambda (x,y):float(x))
# [('1.10e+3', 5), ('1.12e+3', 1), ('1.19e+3', 7)]

I guess you want floats anyways eventually so you can just convert them right away: 我想你最终还是想要漂浮物,所以你可以立即转换它们:

print sorted((float(x),y) for x,y in a.iteritems())
# [(1100.0, 5), (1120.0, 1), (1190.0, 7)]

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

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