user33061
user33061

Reputation: 1895

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)?

Upvotes: 10

Views: 12225

Answers (5)

pboucher
pboucher

Reputation: 352

Not knowing if your items are standardized at 1 digit, 1 space, 1 'x', 1 space, multiple words I wrote this up:

mylist = [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']
def sort(a, b):
  return cmp(" ".join(a.split()[2:]), " ".join(b.split()[2:]))

mylist.sort(sort)

You can edit the parsing inside the sort method but you probably get the idea.

Cheers, Patrick

Upvotes: 2

Justin Standard
Justin Standard

Reputation: 21545

To do so, you need to implement a custom compare:

def myCompare(x, y):
   x_name = " ".join(x.split()[2:])
   y_name = " ".join(y.split()[2:])
   return cmp(x_name, y_name)

Then you use that compare definition as the input to your sort function:

myList.sort(myCompare)

Upvotes: 1

dF.
dF.

Reputation: 75845

How about:

lst.sort(key=lamdba s: s.split(' x ')[1])

Upvotes: 11

S.Lott
S.Lott

Reputation: 392040

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

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

aList.sort( key= myKeyFunc )

Upvotes: 23

Teifion
Teifion

Reputation: 111109

As you are trying to sort what is essentially custom data, I'd go with a custom sort.

Merge sort
Bubble sort
Quicksort

Upvotes: -10

Related Questions