-4

I admit I dont know how to give this question a better title. :-( Anybody has a better idea for the title?

Here is my problem:

I want to sort this list:

a = ['at10', 'at11', 'at12', 'at13', 'at9', 'at1', 'at8']

Every item from the list begins with two letters and has some numbers.

The desired result is as followings. The list is sorted by numbers.

['at1', 'at8', 'at9', 'at10', 'at11', 'at12', 'at13']

I tried with sorted(a) and many of its key settings. But I could not get the result. Anybody please help me out? Thanks in advance!

Rt Rtt
  • 595
  • 2
  • 13
  • 33

2 Answers2

3
sorted(a, key=lambda x:int(x[2:]))
#['at1', 'at8', 'at9', 'at10', 'at11', 'at12', 'at13']
Transhuman
  • 3,527
  • 1
  • 9
  • 15
2

Since your data has a pattern (from index 2 above is a number), you can get each number by defining like getnum (this is one way) function below.

After this, you can use the sorted function in terms of those values (sort by the numbers in the string).

a = ['at10', 'at11', 'at12', 'at13', 'at9', 'at1', 'at8']

def getnum(s):
    num = int(s[2:]);
    return num

b=sorted(a, key = getnum)
print(b)