0

I have multiple list which is arranged by order of importance. I need to do sorting on this list. Important thing is that the last name in the list is important. If there is two 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.

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

>>> mylist.sort()

>>> for x in sorted(mylist):

...     print x

...

K V R Santhosh
R V Laxaman
Ramesh G
Ramesh Ghosh
Srikanth T G

In the above sorting I am getting "Ramesh G" printed first, and my requirement is to print "Ramesh Ghosh" Before "Ramesh G" as below :

K V R Santhosh
R V Laxaman
Ramesh Ghosh
Ramesh G
Srikanth T G

Thank you


I have manged to write the code to sort the name by last name but still not able to find out how to print the last name before any similar name in the list after sort.

#!/bin/python
# sort a list of names by last name

import operator

data = input ("Enter the list: ")

data_as_lists = [ line.split() for line in data ]

data_as_lists.sort(key=operator.itemgetter(-1))

for each_item in data_as_lists :
   print " ".join(each_item)

This code prints the output as below :

python sort_name.py
Enter the list: ["Ramesh G","K V R Santhosh","Srikanth T G", "R V Laxaman","Ramesh Ghosh"]
Ramesh G
Srikanth T G
Ramesh Ghosh
R V Laxaman
K V R Santhosh

The desired output which I want should be like this:

 python sort_name.py
    Enter the list: ["Ramesh G","K V R Santhosh","Srikanth T G", "R V Laxaman","Ramesh Ghosh"]
    Ramesh Ghosh
    Ramesh G
    Srikanth T G
    R V Laxaman
    K V R Santhosh
4

1 回答 1

2

在 python 2.x 中,您可以将cmp参数传递给list.sort方法,您可以在其中实现任何自定义比较函数,例如

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)

输出:

K V R Santhosh
R V Laxaman
Ramesh Ghosh
Ramesh G
Srikanth T G

在 python 3.xcmp中参数已被删除,但您可以使用cmp_to_key在 func 工具中定义

于 2012-04-23T18:27:35.883 回答