📌  相关文章
📜  Python程序按姓氏对姓名列表进行排序

📅  最后修改于: 2022-05-13 01:54:41.017000             🧑  作者: Mango

Python程序按姓氏对姓名列表进行排序

给定一个姓名列表,任务是编写一个Python程序,按姓氏对姓名列表进行排序。

例子:

方法#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))


输出:

方法 #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))

输出: