1

Is there a fast way to sort this list :

list = ['J', 'E', 3, 7, 0]

in order to get this one (numeric first, and then alpha) in python? :

list = [0, 3, 7, 'E', 'J']
10
  • Have you tried using the sort function? list.sort() should do what you want. Commented Oct 4, 2018 at 23:49
  • Side note, never shadow built-ins, e.g. use L or list_ as variable names. Commented Oct 4, 2018 at 23:52
  • Sorry, I've edited my question because my list is a list of tuples so I'm a bit confused with it... Commented Oct 5, 2018 at 0:07
  • Can you update the question with the expected output for the list of tuples example? Commented Oct 5, 2018 at 0:10
  • 1
    I reversed the edit on your question, because if that was your data, you should've said so from the start. Your edit gleefully invalidates every answer here, and that just isn't done, because it isn't fair to the people who've invested time into solving your problem. Now, because of how you framed your question initially, your problem hasn't been solved and our time here has been spent in vain. Please keep this in mind. I recommend opening a new question referencing this one. Commented Oct 5, 2018 at 0:31

3 Answers 3

1

Since you're dealing with numbers (that, in this case, are <10) and strings, you can simplify your key and remove the lambda:

>>> sorted(lst, key=str)
[0, 3, 7, 'E', 'J']

Or, even better, use list.sort for an in-place sorting.

>>> lst.sort(key=str)
>>> lst
[0, 3, 7, 'E', 'J']

Each item will be sorted based on the ASCII value of the str-ified value.

Note that, if you're dealing with numbers >=10 (highly likely), then this solution will end up sorting the numbers lexicographically. To get around that, you will end up needing the lambda.

>>> lst.sort(key=lambda x: (isinstance(x, str), x)))

Which is @jpp's solution.

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

Comments

0

You can sort with a (Boolean, value) tuple:

L = ['J', 'E', 3, 7, 0]

res = sorted(L, key=lambda x: (isinstance(x, str), x))

# [0, 3, 7, 'E', 'J']

Comments

0

If you will use list.sort() on you list, you will get

TypeError: '<' not supported between instances of 'int' and 'str'

You have to convert all items in list into string type.

[str(i) for i in list]

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.