排序python字典

2024-09-29 01:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,里面的值是浮点数。我试图按值的降序对字典进行排序,并试图通过按升序对键进行排序来打破关系。你知道吗

为此,我实现了以下代码:

for key, value in sorted(dictionary.items(), key=lambda x: (-x[1], x[0])):

    print key, value

我的一些价值观似乎不合适。你知道吗

2315 0.000232471518033

2823 0.000232414850716

3649 0.00023239634392

3695 0.00023239634392

3883 0.00023239634392

3479 0.00023239634392

3562 0.00023239634392

3613 0.00023239634392

根据上述代码,以3479开头的行应在以3649开头的行之前打印。你知道吗

对我整理字典的方法有什么问题吗? 这跟浮点数的精度有关系吗?你知道吗


Tags: key代码infordictionary字典排序关系
2条回答

我认为你订购的是这本词典中错误的部分。你可以这样做:

for key, value in sorted(dictionary.items(), key=lambda x: (x[0]):
print key, value

如果您要按键订购,并且

for key, value in sorted(dictionary.items(), key=lambda x: (-x[1]):
print key, value

如果您想按值订购。你知道吗

Has it got anything to do with the precision of floating point numbers?

是的。你知道吗

>>> 0.0002323963439201
0.0002323963439201
>>> print 0.0002323963439201
0.00023239634392

相关问题 更多 >