Python:如何订购float列表

时间:2014-07-01 12:30:37

标签: python

有浮动列表:

a = [465.12, 405.85714285714278, 407.4285714285715, 408.0, 408.1874999999996, 409.875, 411.0, 411.75000000000063, 413.43749999999972, 414.0, 414.66666666666652, 416.33333333333201, 418.0, 417.33333333333252, 419.666666666666, 420.0, 420.74999999999966, 422.70000000000067, 423.0, 423.35714285714295, 425.49999999999994, 426.0, 426.37500000000011, 428.02499999999992, 429.0, 430.03125000000006, 431.8125, 432.0, 432.1874999999996, 434.0625000000004, 435.0, 435.32432432432432, 437.43243243243262, 438.0, 438.39999999999992, 440.40000000000009, 441.0, 441.32432432432427, 442.9459459459456, 444.0, 444.42857142857122, 445.97142857142865, 447.0, 447.92857142857116, 450.0, 450.0, 450.60000000000002, 452.72727272727263, 453.0, 453.19148936170194, 454.78723404255322, 456.0, 456.5, 458.5, 459.0, 459.44999999999959, 461.40000000000015, 462.0, 462.50000000000023, 464.16666666666725]

我试图通过后代值对该列表进行排序(请注意我需要ind,因为稍后我将使用它对其他列表进行排序,例如sorted_b):

ind = sorted(range(len(a)), key = lambda i:a[i], reverse = True)

sorted_a = [x for (i, x) in sorted(zip(ind, a))]

# sorted_b = [x for (i, x) in sorted(zip(ind, b))]

但是代码不能像我期望的那样工作:

>>> sorted_a
[465.12, 464.16666666666725, 462.5000000000002, 462.0, 461.40000000000015, 459.4499999999996, 459.0, 458.5, 456.5, 456.0, 454.7872340425532, 453.19148936170194, 452.72727272727263, 453.0, 450.6, 450.0, 450.0, 447.92857142857116, 447.0, 445.97142857142865, 444.4285714285712, 444.0, 442.9459459459456, 441.32432432432427, 441.0, 440.4000000000001, 438.3999999999999, 438.0, 437.4324324324326, 435.3243243243243, 435.0, 434.0625000000004, 432.1874999999996, 432.0, 431.8125, 430.03125000000006, 429.0, 428.0249999999999, 426.3750000000001, 426.0, 425.49999999999994, 423.35714285714295, 423.0, 422.70000000000067, 420.0, 420.74999999999966, 419.666666666666, 417.3333333333325, 418.0, 416.333333333332, 414.6666666666665, 414.0, 413.4374999999997, 411.7500000000006, 411.0, 409.875, 408.1874999999996, 408.0, 407.4285714285715, 405.8571428571428]

有些值未正确排序,我们可以在图中轻松看到:

import matplotlib.pyplot as mpl
mpl.plot(sorted_a)
mpl.show()

Bad sorting

我做错了什么?

2 个答案:

答案 0 :(得分:3)

sorted(zip(ind, a))

对来自(index, value)的{​​{1}}对进行词典排序;由于整数索引在结构上都是唯一的,因此排序甚至不会查看值并只对索引进行排序。你的意思是

zip

或更好,如果NumPy是一个选项:

[a[i] for i in ind]

答案 1 :(得分:2)

首先正确形成排序顺序:

ind = sorted(range(len(a)), key = lambda i:a[i], reverse = True)

但是如果你想要排序a,你就可以轻松得到它:

[ a[i] for i in ind ]

也许这有帮助?