sorting floats numerically - not in ascii order - in python
This might sound like a silly question, but I've tried to find an answer that works without much success. I've got a list of lists:
for v in sorted(list):
print v
[885.1, 12824]
[885.1, 19843]
[885.11, 开发者_如何学C1319]
[885.12, 1155]
[885.13, 12844]
[885.14, 33602]
[885.15, 11324]
[885.16, 44040]
[885.2, 119283]
[885.3, 8424]
I've iterated through my list using the sorted function - however that brings up the items in ASCII order as above - can they be sorted as floats in a human readable order? ie:
[885.1, 19843]
[885.2, 119283]
[885.3, 8424]
[885.11, 1319]
[885.12, 1155]
[885.13, 12844]
[885.14, 33602]
[885.15, 11324]
[885.16, 44040]
Do I need to create an index of somekind? Convert my floats to ints? Any help much appreciated.
David.
convert the float to string first and split it by ".":
sorted(a, key=lambda x:map(int, str(float(x[0])).split(".")))
This is called a "natsort" (natural sort). A quick google on it gives me this: http://www.skynet.ie/~caolan/Packages/python-natsort.html (haven't tried it though). Maybe it helps you.
Oh and that's not necessarily ASCII sort, it's just the number order, you know, like the real axis
You need to give sorted a comparison function. Something like the following:
sorted(list, cmp=lambda x, y: cmp(x[0], y[0]))
Just write the function you need for what you want and plug it in.
You'll probably want something like a reverse radix sort.
This is kind of a hack, but:
a = [
[885.1, 19843],
[885.1, 12824],
[885.11, 1319],
[885.12, 1155],
[885.13, 12844],
[885.14, 33602],
[885.15, 11324],
[885.16, 44040],
[885.2, 119283],
[882.8, 8424],
[882.75, 8424],
[885.3, 8424]
]
for v in sorted(a, key=lambda t: str(t[0]).split(".")[0] + ("%05d" % int(str(t[0]).split(".")[1])) + "," + str(t[1])):
print v
Result is
[882.8, 8424]
[882.75, 8424]
[885.1, 12824]
[885.1, 19843]
[885.2, 119283]
[885.3, 8424]
[885.11, 1319]
[885.12, 1155]
[885.13, 12844]
[885.14, 33602]
[885.15, 11324]
[885.16, 44040]
Disclaimer: this assumes at most 5 places after the decimal point. Adjust accordingly.
精彩评论