我有多个列表,按重要性顺序排列。我需要对此列表进行排序。重要的是列表中的姓氏很重要。如果列表中有两个与姓氏相似的名称,则应首先打印姓氏。此外,我需要确保字母表案例在排序后不会更改。
>>> 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
在上面的排序中,我首先打印“Ramesh G”,我的要求是在“Ramesh G”之前打印“Ramesh Ghosh”,如下所示:
K V R Santhosh
R V Laxaman
Ramesh Ghosh
Ramesh G
Srikanth T G
谢谢
我已经编写代码来按姓氏对名称进行排序,但仍然无法找到如何在排序后列表中的任何类似名称之前打印姓氏。
#!/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)
此代码打印输出如下:
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
我想要的输出应该是这样的:
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
答案 0 :(得分: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.x cmp
参数已被删除,但您可以使用func工具中定义的cmp_to_key