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']