0

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, 1319]
[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.

2
  • 7
    The original sort is already ordered numerically - 885.16 is less than 885.2(0) Commented Sep 7, 2011 at 6:06
  • In your input list you have two values in which 885.1 appears first. I assume you want those to both appear in your output, right? And you want them to be considered when sorting, correct? Commented Sep 7, 2011 at 6:25

4 Answers 4

3

convert the float to string first and split it by ".":

sorted(a, key=lambda x:map(int, str(float(x[0])).split(".")))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.