I tried to sort using sorted
dir =["A1","A2","A10","A3"]
sorted(dir)
My expected array is
["A1","A2","A3","A10"]
but actual result is
["A1", "A10", "A2", "A3"]
How to sort array by name in python ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is sorting by alphabetical order, so you need to break up the numbers and convert them to ints and sort with that. (Numbers in strings are treated as just characters, so it “sees” “A10” and tries to sort it first by “A”, then by “1”, and then by “0.”) For example:
If you are going to have other letters besides “A” in
dir, you’ll need a more complicated sorting method, but it will be something along the same lines. (If you explain whatdircontains more, I can write an example for that.) As mgilson’s comment points out, if the elements ofdirfollow the 1 char + number format, then you could take advantage of tuple sorting and do something like this: