Python中如何删除列表中的重复项?
作者:小宇宙叶知秋
时间:2023-10-27
浏览:1
要从Python中的列表中删除重复项,我们可以使用本文中讨论的各种方法。使用字典从列表中删除重复项示例在此示例中,我们将使用OrderedDict从列表中删除重复项-fromcollectionsimportOrderedDict#CreatingaListwithduplicateitemsmylist=["Jacob","Harry","Mark","Anthony","Harry","Anthony"]#DisplayingtheListprint("List=",mylist)#Removedup
本文目录
要从 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']
作者最新文章
Wattpad小说阅读平台官网地址:最新PC端网页版入口
2026-11-16 16:59
Yandex官网入口及网页版访问教程
2026-11-14 09:47
12306APP退票扣多少钱48小时和24小时差别
2026-11-10 16:08
蛙蛙写作在线使用网址:电脑网页端登录入口直达
2026-11-10 10:18
笔趣阁在线阅读免费无弹窗小说网站入口教程
2026-11-05 08:38
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































