Python程序按姓氏对姓名列表进行排序
给定一个姓名列表,任务是编写一个Python程序,按姓氏对姓名列表进行排序。
例子:
Input: [‘John Wick’, ‘Jason Voorhees’]
Output: [‘Jason Voorhees’, ‘John Wick’]
Explanation: V in Voorhees of Jason Voorhees is less than W in Wick of John Wick.
Input: [‘Freddy Krueger’, ‘Keyser Söze’,’Mohinder Singh Pandher’]
Output: [‘Freddy Krueger’, ‘Mohinder Singh Pandher’, ‘Keyser Soze’]
Explanation: K< P < S
方法#1:对转换后的二维列表使用sorted()方法。
将姓名列表转换为二维姓名列表,其中第一个索引代表名字,最后一个索引代表姓氏。应用sorted()方法,将键作为 2D 列表中每个元素的最后一个索引。
Python3
# explicit function sort names
# by their surnames
def sortSur(nameList):
l2 = []
# create 2d list of names
for ele in nameList:
l2.append(ele.split())
nameList = []
# sort by last name
for ele in sorted(l2, key=lambda x: x[-1]):
nameList.append(' '.join(ele))
# return sorted list
return nameList
# Driver Code
# assign list of names
nameList = ['John Wick', 'Jason Voorhees',
'Freddy Krueger', 'Keyser Soze',
'Mohinder Singh Pandher']
# display original list
print('\nList of Names:\n', nameList)
print('\nAfter sorting:\n', sortSur(nameList))
Python3
# explicit function sort names
# by their surnames
def sortSur(nameList):
# sort list by last name
nameList.sort(key=lambda x: x.split()[-1])
# return sorted list
return nameList
# Driver Code
# assign list of names
nameList = ['John Wick', 'Jason Voorhees',
'Freddy Krueger', 'Keyser Soze',
'Mohinder Singh Pandher']
# display original list
print('\nList of Names:\n', nameList)
print('\nAfter sorting:\n', sortSur(nameList))
输出:
List of Names:
[‘John Wick’, ‘Jason Voorhees’, ‘Freddy Krueger’, ‘Keyser Soze’, ‘Mohinder Singh Pandher’]
After sorting:
[‘Freddy Krueger’, ‘Mohinder Singh Pandher’, ‘Keyser Soze’, ‘Jason Voorhees’, ‘John Wick’]
方法 #2:使用sort()方法 + lambda
对给定的名称列表使用sort()方法,键为lambda x: x.split()[-1])表示列表中每个元素中的最后一个字符串。
蟒蛇3
# explicit function sort names
# by their surnames
def sortSur(nameList):
# sort list by last name
nameList.sort(key=lambda x: x.split()[-1])
# return sorted list
return nameList
# Driver Code
# assign list of names
nameList = ['John Wick', 'Jason Voorhees',
'Freddy Krueger', 'Keyser Soze',
'Mohinder Singh Pandher']
# display original list
print('\nList of Names:\n', nameList)
print('\nAfter sorting:\n', sortSur(nameList))
输出:
List of Names:
[‘John Wick’, ‘Jason Voorhees’, ‘Freddy Krueger’, ‘Keyser Soze’, ‘Mohinder Singh Pandher’]
After sorting:
[‘Freddy Krueger’, ‘Mohinder Singh Pandher’, ‘Keyser Soze’, ‘Jason Voorhees’, ‘John Wick’]