Python程式:按姓氏排序姓名列表


在這篇文章中,我們將學習一個 Python 程式,用於按姓氏對姓名列表進行排序。

使用的方法

  • 使用 lambda 和 sorted() 函式

  • 使用 lambda 和 sort() 函式

示例

假設我們已經獲取了一個包含字串元素的**輸入列表**。現在,我們將使用上述方法按姓氏的字母順序(升序)對列表元素進行排序。

輸入

Input List: ['sachin tendulkar', 'suresh raina', 'hardik pandya']

輸出

Input List after sorting by last names:
['hardik pandya', 'suresh raina', 'sachin tendulkar']

輸入列表元素的姓氏依次為 tendulkar、raina、pandya,即**t、r、p**(首字母順序)。我們將它們按姓氏的字母順序升序排序,這意味著**p、r、t**(p

方法 1:使用 lambda 和 sorted() 函式

Lambda 函式

Lambda 函式,通常稱為“**匿名函式**”,與普通的 Python 函式相同,只是它可以**無需名稱**地定義。**def** 關鍵字用於定義普通函式,而**lambda** 關鍵字用於定義匿名函式。但是,它們僅限於單行表示式。它們與普通函式一樣,可以接受多個引數。

語法

lambda arguments: expression

sorted() 函式

**sorted()** 函式返回給定可迭代物件的排序列表。

您可以選擇升序或降序。數字按數值排序,而字串按字母順序排序。

語法

sorted(iterable, key=key, reverse=reverse)

引數

  • **iterable** - 它是一個序列,例如元組、列表、字串等。

  • **key** - 將執行以確定順序的函式。預設值為 None。

  • **reverse** - 布林表示式。**True** 表示升序排序,**False** 表示降序排序。預設值為 False。

演算法(步驟)

以下是執行所需任務的演算法/步驟。

  • 建立一個函式**sortBySurnames()**,該函式透過接受字串輸入列表作為引數來按姓氏對列表進行排序。

  • 建立一個空列表來儲存姓名列表。

  • 使用**for 迴圈**遍歷輸入列表。

  • 使用**split() 函式**(將字串拆分為列表。我們可以定義分隔符;預設分隔符是任何空格)將當前單詞拆分為單詞列表。

  • 使用**append() 函式**(在列表末尾新增元素)將其追加到上述空列表中。

  • 再次修改輸入列表為空,以儲存結果。

  • 透過使用第二個單詞(姓氏)作為鍵進行排序,遍歷新列表的排序結果。

  • 使用**join()** 函式將其轉換為字串,並使用 append() 函式將其追加到輸入列表中。

  • 返回按姓氏排序的結果列表。

  • 建立一個變數來儲存字串的**輸入列表**,並列印給定列表。

  • 透過將輸入列表作為引數,呼叫上面定義的**sortBySurnames()** 函式。

示例

以下程式使用 lambda 函式和 sorted() 方法返回按輸入列表姓氏排序的列表。

# creating a function that sorts the list by the last name

# by accepting the input list of strings as an argument
def sortBySurnames(inputList):
   
   # storing the list of names
   newList = []
   
   # traversing through an input list
   for i in inputList:
      
      # splitting the current word into the list of words and
      
      # appending into an above created empty list
      newList.append(i.split())
   
   # making the input list empty again
   inputList = []
   
   # Traversing in the sorted of the new list by sorting with key as second word(lastname)
   for i in sorted(newList, key=lambda k: k[-1]):
      
      # converting to a string using join() and appending it to input list
      inputList.append(' '.join(i))
   
   # returning the sorted list by last names
   return inputList

# input list of names
inputList = ['sachin tendulkar', 'suresh raina', 'hardik pandya']

# printing input list
print('Input List:', inputList)

# calling the sortBySurnames() function by passing the input list as argument
print('Input List after sorting by last names:\n', sortBySurnames(inputList))

輸出

執行上述程式後,將生成以下輸出。

Input List: ['sachin tendulkar', 'suresh raina', 'hardik pandya']
Input List after sorting by last names:
['hardik pandya', 'suresh raina', 'sachin tendulkar']

方法 2:使用 lambda 和 sort() 函式

sort() 方法

**sort()** 方法就地對原始列表進行排序。這意味著 sort() 方法會更改列表元素的順序。

預設情況下,sort() 方法使用小於運算子 (<) 對列表的條目進行排序,即**升序**。換句話說,它優先考慮較小的元素而不是較大的元素。

要從最高到最低(**降序**)排序元素,請在 sort() 方法中使用 reverse=True 引數。

list.sort(reverse=True)

示例

以下程式使用 lambda 函式和 sort() 方法返回按輸入列表姓氏排序的列表。

# creating a function that sorts the input list by surnames

# by accepting the list as an argument
def sortBySurnames(inputList):
   
   # Splitting the input list and sorting with the key as the second word
   inputList.sort(key=lambda k: k.split()[-1])
   
   # returning the sorted list by last names
   return inputList

# input list of names
inputList = ['sachin tendulkar', 'suresh raina', 'hardik pandya']

# printing input list
print('Input List:', inputList)

# calling the sortBySurnames() function bypassing the input list as an argument
print('Input List after sorting by last names:\n', sortBySurnames(inputList))

輸出

執行上述程式後,將生成以下輸出。

Input List: ['sachin tendulkar', 'suresh raina', 'hardik pandya']
Input List after sorting by last names:
['hardik pandya', 'suresh raina', 'sachin tendulkar']

結論

本文介紹了兩種不同的按姓氏對姓名列表進行排序的方法。我們學習瞭如何在 sorted() 和 sort() 函式中使用 key 引數根據第 n 個單詞或字元進行排序。此外,我們還學習瞭如何使用 join() 函式連線列表並將其轉換為字串。

更新於: 2023年1月27日

1K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告