如何從 Python 中的列表中移除重複項?


要從 Python 中的一個列表中移除重複項,我們可以使用本文所討論的多種方法。

使用字典從一個列表中移除重複項

示例

在該示例中,我們將使用 OrderedDict 從列表中移除重複項 -

from collections import OrderedDict # Creating a List with duplicate items mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"] # Displaying the List print("List = ",mylist) # Remove duplicates from a list using dictionary resList = OrderedDict.fromkeys(mylist) # Display the List after removing duplicates print("Updated List = ",list(resList))

輸出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Jacob', 'Harry', 'Mark', 'Anthony']

使用列表推導從一個列表中移除重複項

示例

在該示例中,我們將使用列表推導從列表中移除重複項 

# Creating a List with duplicate items mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"] # Displaying the List print("List = ",mylist) # Remove duplicates from a list using List Comprehension resList = [] [resList.append(n) for n in mylist if n not in resList] print("Updated List = ",resList)

輸出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Jacob', 'Harry', 'Mark', 'Anthony']

使用集合從一個列表中移除重複項

示例

在該示例中,我們將使用 set() 方法從列表中移除重複項 -

# Creating a List with duplicate items mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"] # Displaying the List print("List = ",mylist) # Remove duplicates from a list using Set resList = set(mylist) print("Updated List = ",list(resList))

輸出

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Anthony', 'Mark', 'Jacob', 'Harry']

上次更新時間: 2022-09-16

428 瀏覽

開啟您的事業

完成課程獲得認證

開始
廣告