# Sort names in a list by order of importance

**URL:** <https://community.unix.com/t/sort-names-in-a-list-by-order-of-importance/308910>\
**Category:** Shell Programming and Scripting\
**Created:** [April 23, 2012, 6:12pm UTC](https://community.unix.com/t/sort-names-in-a-list-by-order-of-importance/308910 "2012-04-23T18:12:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pratapsingh](https://community.unix.com/letter_avatar/pratapsingh/32/5_5575768a8748004e209b776fc1b2916d.png) [@pratapsingh](https://community.unix.com/u/pratapsingh)\
**Post date:** [April 23, 2012, 6:12pm UTC](https://community.unix.com/t/sort-names-in-a-list-by-order-of-importance/308910/1 "2012-04-23T18:12:42Z")

</div>

Hi,

I have multiple list which is arranged by order of importance. I need to do sorting on these lists based on the last name of the user(initial), if user name does not have initial then first name is initial . Important thing is that the last name in the list is important. If there is two or more similar name as the last name in the list then the last name should be printed first. Also I need to make sure that alphabets case do not change after sorting.

```nohighlight
def mycmp(a, b):

    if a.startswith(b):

        return -1

    return cmp(a, b)

mylist = ["Ramesh G","K V R Santhosh","Srikanth T G", "R V Laxaman","Ramesh Ghosh"]

mylist.sort(cmp=mycmp)

print "\n".join(mylist)

Output:

K V R Santhosh

R V Laxaman

Ramesh Ghosh

Ramesh G

Srikanth T G

```

Above works fine but in the scenario mentioned below it fails :

```nohighlight
>>> mylist = ["Alan","aLan","alAn","alaN","ALan","AlAn","AlaN","aLAn","aLaN","alAN"] 
>>> mylist.sort(cmp=mycmp) 
>>> print "\n".join(mylist) 
ALan AlAn AlaN Alan aLAn aLaN aLan alAN alAn alaN 

```

The desired output should be like this :

```nohighlight
["alAN", "aLaN", "aLAn", "AlaN", "AlAn", "ALan", "alaN", "alAn", "aLan", "Alan"]

```

Any clue how can we do this?

---

<div class="post-metadata">

**Author:** ![Chubler\_XL](https://community.unix.com/user_avatar/community.unix.com/chubler_xl/32/2077_2.png) [@Chubler\_XL](https://community.unix.com/u/Chubler_XL)\
**Post date:** [April 23, 2012, 7:28pm UTC](https://community.unix.com/t/sort-names-in-a-list-by-order-of-importance/308910/2 "2012-04-23T19:28:34Z")

</div>

Append the ordinal position before sorting and remove it after.

eg sort this:

```nohighlight
["Alan_1","aLan_2","alAn_3","alaN_4","ALan_5","AlAn_6","AlaN_7","aLAn_8","aLaN_9","alAN_10"] 

```

And strip the "\_[0-9]\*$" after the sort is done
