如何从 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']
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP