1

I have a list of strings that contains salutation in it. How can I sort the list on the basis of names (after salutation - Mr., Ms., Mrs.) in pythonic way?

I have tried to split the elements of list on the basis of '.' character and sorted the names but could not get salutation with sorted names.

names = ["Mr.usman", "Mrs.obama", "Mr.Albert"]
sorted_list = sorted([i.split('.')[1] for i in names])

For e.g ["Mr.usman", "Mrs.obama", "Mr.Albert"] should be like ["Mr.Albert", "Mrs.obama", "Mr.usman"]

Any help is highly appreciated.

Salman Khakwani
  • 6,684
  • 7
  • 33
  • 58
Malik Faiq
  • 433
  • 6
  • 18

2 Answers2

5

You should not sort the manipulated list, you can specify the key=... parameter to determine on what to sort, like:

sorted_list = sorted(names, key=lambda n: n.split('.', 2)[1].casefold())

This yields:

>>> sorted(names, key=lambda n: n.split('.', 2)[1].casefold())
['Mr.Albert', 'Mrs.obama', 'Mr.usman']

The .casefold() is used to do a case-insensitive comparison, which your question sample output suggests. You can remove it if you want case sensitive comparisons.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
3

You can do like this:

names = ['Mr.Osama', 'Mrs.Usman', 'Mr.Ali', 'Mrs.Ghani']
sortedList = sorted(names, key=lambda elem: elem[3:] if 'Mr.' in elem else elem[4:])
print('Sorted list:', sortedList)
  • According to the data in the question we have names starting with uppercase and lowercase. I'd do: `sorted(names, key=lambda name:name.lower().split('.')[1])` – Matthias Aug 20 '19 at 08:25
  • @MalikFaiq in that case sorted(names, key=lambda name:name.lower().split('.')[1]), this would be good solution. – Osama Rasheed Aug 20 '19 at 08:29
  • @OsamaRasheed: please use `casefold()` over `lower()`: https://stackoverflow.com/questions/45745661/python-lower-vs-casefold-in-string-matching-and-converting-to-lowercase – Willem Van Onsem Aug 20 '19 at 08:39