Sean
Sean

Reputation: 1

how to sort items in a list alphabetically by the letters in their respective names.

I am trying to sort values in a list by the letters in their name: I want, for example, ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?

Upvotes: 0

Views: 113

Answers (6)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

trying to sort values in a list by the letters in their name

The example you mentioned is very simple. Based on your requirement, below is the code using re.findall() and sorted() to sort based on letters in any order within string:

>>> import re
>>> s = ['a9d', '1a2ba', '1e2s', '1b3tr']
>>> sorted(s, key=lambda x: re.findall("[a-zA-Z]+", x))
['1a2ba', 'a9d', '1b3tr', '1e2s']  # Sorted based on: aba, ad, btr, es

Upvotes: 0

Ben Quigley
Ben Quigley

Reputation: 727

The .sort() method for lists has been mentioned; there's a sorting function that takes the list as an argument, and returns a sorted list without modifying the list in place:

>>> mylist = ["8a", "8c", "8b", "8d"]
>>> sorted(list)
['8a', '8b', '8c', '8d']
>>> mylist
['8a', '8c', '8b', '8d']

Upvotes: 0

gowrath
gowrath

Reputation: 3224

Assuming your format is always number followed by letter, you need to give the sort method a specific key to sort by: in this case you want to sort by the last character. A lot of the other answers are just sorting your list alphabetically using the number followed by letter whereas I get the feeling you only want to sort by the letter. This is one possible way:

 s = ['9d', '12a', '1e']
 sorted_s = sorted(s, key=lambda x:x[-1])   # sorts by the last character of every entry

This will return:

['12a', '9d', '1e']

Upvotes: 1

Matthias
Matthias

Reputation: 13232

The answer is easy if the data looks like in your question. If the data is more complex you will have to give the sort method a key which contains only characters from the alphabet.

data =  ["34b", "2a5t", "2a5s", "abcd"]
data.sort(key=lambda x: ''.join(c for c in x if c.isalpha()))
print(data)

This will give you ['abcd', '2a5s', '2a5t', '34b'].

If you want to see how the constructed key looks like you can check it like this:

for value in data:
    print(value, ''.join(c for c in value if c.isalpha()))

34b b
2a5t at
2a5s as
abcd abcd

Upvotes: 3

wagnerdelima
wagnerdelima

Reputation: 360

That would solve solve your problem:

_list = ["8a", "8c", "8b", "8d"] 
_list.sort()
print _list

Output:

['8a', '8b', '8c', '8d']

Upvotes: 0

Xavid Ramirez
Xavid Ramirez

Reputation: 216

You can accomplish this by sorting it by a list.

list = ["8a", "8c", "8b", "8d"] 
list.sort()
print(list)

Upvotes: 0

Related Questions