为什么排序混合列表不起作用

时间:2018-01-20 09:35:54

标签: python-3.x

在这段时间里,我一直在摸不着头脑:

   public static void show(String titleString, String messageString, AlertType status, String iconStr)
    {                
        Alert alert = new Alert(status);
        alert.initStyle(StageStyle.UTILITY);
        alert.setTitle(titleString);
        alert.setHeaderText("");
        alert.setContentText(messageString);


        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int centerX = screenSize.width/2;
        int centerY = screenSize.height/2;

        alert.setX(centerX);
        alert.setY(centerY);
        alert.showAndWait();
    }

预期输出为:

mixed = [-131.23, 33213, 4454, 566, -33, 465. -377.312, 5.6656]
print(sorted(mixed, key=float))

相反,我总是得到这个

[-131.23, -377.312, -33, 5.6656, 566, 4454, 33213]

为什么-337.312会转换为87.6879999999 ??我假设当使用key = float时,每个元素都被转换为float ...那么为什么会出现这种情况?

1 个答案:

答案 0 :(得分:2)

问题在于原始数据:

>>> [-131.23, 33213, 4454, 566, -33, 465. -377.312, 5.6656]
[-131.23, 33213, 4454, 566, -33, 87.68799999999999, 5.6656]

因为你忘记了逗号,这就是减法:

>>> 465. -377.312
87.68799999999999

只需添加逗号:

>>> sorted([-131.23, 33213, 4454, 566, -33, 465, -377.312, 5.6656])
[-377.312, -131.23, -33, 5.6656, 465, 566, 4454, 33213]