Python 按重要性顺序对列表中的名称进行排序
我有多个列表,按重要性顺序排列。我需要在这个列表上排序。重要的是名单上的姓氏很重要。如果列表中有两个与姓氏相似的名字,则应首先打印姓氏。此外,我需要确保字母大小写在排序后不会改变Python 按重要性顺序对列表中的名称进行排序,python,sorting,Python,Sorting,我有多个列表,按重要性顺序排列。我需要在这个列表上排序。重要的是名单上的姓氏很重要。如果列表中有两个与姓氏相似的名字,则应首先打印姓氏。此外,我需要确保字母大小写在排序后不会改变 >>> mylist = ["Ramesh G","K V R Santhosh","Srikanth T G", "R V Laxaman","Ramesh Ghosh"] >>> mylist.sort() >>> for x in sorted(mylis
>>> 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
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
多谢各位
我已经设法编写了按姓氏排序的代码,但仍然无法找到如何在排序后在列表中的任何类似名称之前打印姓氏
#!/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)
此代码按如下方式打印输出:
K V R Santhosh
R V Laxaman
Ramesh Ghosh
Ramesh G
Srikanth T G
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
在Python2.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
在Python3.x
cmp
中,参数已被删除,但您可以使用func tools中定义的感谢您在以下情况下的输入,它无法按照要求打印结果。>>>mylist=[“Alan”、“Alan”、“Alan”、“Alan”、“Alan”、“Alan”、“Alan”、“Alan”]>>>mylist.sort(cmp=mycmp)>>>打印“\n”。加入(mylist)Alan Alan所需的输出应如下所示:[“Alan”、“Alan”、“Alan”、“Alan”、“Alan”、“Alan”,“alAn”、“alAn”、“alAn”]@PratapSingh根据您的要求修改cmp函数,我已经展示了一个如何实现的示例