简体   繁体   中英

How to sort strings containing numbers and letters?

I have a list in the following form:

['AK 40', 'AK 35', 'AK 20', '2012',
'2011', '2010', '2009', '2009',
'2007', '2006', '2006', '2005',
'2004', '2003', '2003', '2002']

Those years all represent birthyears and groupings of ages. What I need is to sort them in the following form:

['2012', '2011', '2010', ... , '2003', '2002', 'AK 20', 'AK 35', 'AK 40']

Basically, the years should be descending, from the youngest person to the oldest. But starting from age twenty they need to be treated differently.

I already tried some lambda functions I found here on stackoverflow, but unfortunately none of them worked for me due to the fact that my list contains only strings and is not mixed with integers.

If your strings share the same prefix ( AK in this case), you can use the following lambda function:

sort_func = lambda e : -int(e) if e.isdigit() else int(''.join(filter(str.isdigit, e)))

sorted_list = sorted(l, key = sort_func)

Where l is your initial list, for your example, this outputs:

['2012', '2011', '2010', '2009', '2009', '2007', '2006', '2006', '2005', '2004', '2003', '2003', '2002', 'AK 20', 'AK35', 'AK 40']

The above functions sorts first by the year strings (the - in -len(e) is used to sort them in descending order), then, it sorts the age groups in ascending order by the number after the prefix AK (by filtering out anything that's not a digit from the age groups' strings).

seq = ['AK 40', 'AK 35', 'AK 20', '2012', '2011', '2010', '2009', '2009',
       '2007', '2006', '2006', '2005', '2004', '2003', '2003', '2002']

years = [year for year in seq if year.isdigit()]
aks = [ak for ak in seq if not ak.isdigit()]
years.sort()
aks.sort()
result = years[::-1] + aks
print(result)
x = ['AK 40', 'AK 35', 'AK 20', '2012', '2011', '2010', '2009', '2009', '2007', '2006', '2006', '2005', '2004', '2003', '2003', '2002']

简短将是

sorted_list = sorted(x, key = lambda e : int(e.replace('AK ', '-')), reverse=True)

You can use a simple sort key:

d = ['AK 40', 'AK 35', 'AK 20', '2012', '2011', '2010', '2009', '2009', '2007', '2006', '2006', '2005', '2004', '2003', '2003', '2002']
new_d = sorted(d, key=lambda x:[1, -1][x.isdigit()]*int(x.split()[-1]))

Output:

['2012', '2011', '2010', '2009', '2009', '2007', '2006', '2006', '2005', '2004', '2003', '2003', '2002', 'AK 20', 'AK 35', 'AK 40']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM