Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, sorting a list by a key that's a substring of each element

Part of a programme builds this list,

[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale']

I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?

like image 881
user33061 Avatar asked Jan 13 '09 19:01

user33061


People also ask

How do you sort a list by substring in Python?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .

How do you sort a list in Python by element?

sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order. sort() accepts two optional parameters. reverse is the first optional parameter.


1 Answers

You have to get the "key" from the string.

def myKeyFunc( aString ):
    stuff, x, label = aString.partition(' x ')
    return label

aList.sort( key= myKeyFunc )
like image 151
S.Lott Avatar answered Nov 11 '22 15:11

S.Lott