您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python中如何删除列表中的重复项?

2025/6/12 20:13:24发布16次查看
要从 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中如何删除列表中的重复项?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product