1

How would I sort this?

>>> list = ["a_0","a_1","a_2","a_3","a_10","a_11","a_23","a_5","a_6","a_5"]
>>> sorted(list)
['a_0', 'a_1', 'a_10', 'a_11', 'a_2', 'a_23', 'a_3', 'a_5', 'a_5', 'a_6']>

What I need it to be is:

['a_0', 'a_1', 'a_2', 'a_3', 'a_5', 'a_5', 'a_6, 'a_10', 'a_11', 'a_23']>

So it's sorted based on the "number".

0

2 Answers 2

10

do you mean this: sorted(list, key=lambda d: int(d[2:])) ?

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this will sort only based on the number, and not on the 'a' at all. It also requires that the digits start at character 2.
"Note that this will sort only based on the number", indeed
6

You need to write a "key function" that translates your string into a search key that has the ordering you want. For example:

def key(k):
    s, sep, i = k.partition('_')
    return (s, int(i))

>>> L = ["a_0","a_1","b_2","c_2","a_10","a_11","a_23","b_5","a_6","c_5"]
>>> sorted(L, key=key)
['a_0', 'a_1', 'a_6', 'a_10', 'a_11', 'a_23', 'b_2', 'b_5', 'c_2', 'c_5']

1 Comment

thanks, this is actually what I needed for my exact purpose. I changed it a bit, now works perfect. Although your answer is correct, I have marked the answer above correct based on the question.

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.