首頁  >  文章  >  後端開發  >  Python中如何刪除清單中的重複項目?

Python中如何刪除清單中的重複項目?

PHPz
PHPz原創
2023-08-25 16:57:281992瀏覽

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 從清單中刪除重複項

範例

在此範例中,我們將使用 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']

以上是Python中如何刪除清單中的重複項目?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn