6种在 Python 中从 List 中删除重复项的方法

本文介绍了六种Python方法删除列表中的重复项:简单遍历、列表推导式、利用set、列表理解+enumerate、OrderedDict.fromkeys和处理嵌套列表。这些方法各有优缺点,适用于不同场景,帮助开发者提高编程效率。
摘要由CSDN通过智能技术生成

Python从列表中删除重复项的方法,在本文中列出了6种方法,这些方法在许多应用程序中都会遇到。作为程序员,我们最好了解它们,以便在需要时编写有效的程序。

方法1:最简单容易的方法

此方法基于遍历整个列表,将第一个元素添加到新列表中。

# Python 3 code to demonstrate # removing duplicated from list # using naive methods 
# initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print ("The original list is : " +  str(test_list))
# using naive method to remove duplicated from list res = []for i in test_list:    if i not in res:        res.append(i)
# printing list after removal print ("The list after removing duplicates : " + str(res))

 输出结果:

原始列表是:[1, 3, 5, 6, 3, 5, 6, 1]

删除重复项后的列表:[1, 3, 5, 6]

方法2:理解列表

这个方法其实是第一种方法的简化版,它使用了列表推导式,可以用一行代码代替上面的循环方法。

# Python 3 code to demonstrate # removing duplicated from list # using naive methods 
# initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print ("The original list is : " +  str(test_list))
# using naive method to remove duplicated from list res = []for i in test_list:    if i not in res:        res.append(i)
# printing list after removal print ("The list after removing duplicates : " + str(res))

方法3:使用 set()

这是从列表中删除重复元素的最流行的方法。但是,这种方法最大的缺点之一是set后列表中元素的顺序不再和原来一样。

# Python 3 code to demonstrate # removing duplicated from list # using set()
# initializing listtest_list = [1, 5, 3, 6, 3, 5, 6, 1]print ("The original list is : " +  str(test_list))
# using set()to remove duplicated from list test_list = list(set(test_list))
# printing list after removal # distorted orderingprint ("The list after removing duplicates : " + str(test_list))

输出结果:

原始列表是:[1, 5, 3, 6, 3, 5, 6, 1]

删除重复项后的列表:[1, 3, 5, 6]

方法 4:使用列表理解 + enumerate()

此方法使用枚举根据列表理解删除重复元素。通过检查该元素是否已存在于列表中来跳过该元素。此方法保持列表中元素的顺序。

示例代码:

# Python 3 code to demonstrate # removing duplicated from list # using list comprehension + enumerate()
# initializing listtest_list = [1, 5, 3, 6, 3, 5, 6, 1]print ("The original list is : " +  str(test_list))
# using list comprehension + enumerate()# to remove duplicated from list res = [i for n, i in enumerate(test_list) if i not in test_list[:n]]
# printing list after removal print ("The list after removing duplicates : " + str(res))

方法 5:使用 collections.OrderedDict.fromkeys()

这是完成特殊任务的最快方式。它首先删除列表中的重复项并返回一个字典,最后将其转换为列表。此方法也可用于字符串,之后列表中元素的顺序也发生了变化。

# Python 3 code to demonstrate # removing duplicated from list # using collections.OrderedDict.fromkeys()from collections import OrderedDict
# initializing listtest_list = [1, 5, 3, 6, 3, 5, 6, 1]print ("The original list is : " +  str(test_list))
# using collections.OrderedDict.fromkeys()# to remove duplicated from list res = list(OrderedDict.fromkeys(test_list))
# printing list after removal print ("The list after removing duplicates : " + str(res))

方法 6:处理嵌套列表中的重复元素

用于多维列表(列表嵌套)重复元素移除。这里假设列表(也是一个列表)中具有相同元素(但不一定是相同顺序)的元素被认为是重复的。然后使用下面的 set() + sorted() 方法完成任务。

# Python3 code to demonstrate# removing duplicate sublist # using set() + sorted()
# initializing listtest_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1],                           [1, 2, 3], [3, 4, 1]]
# printing original listprint("The original list : " + str(test_list))
# using set() + sorted()# removing duplicate sublistres = list(set(tuple(sorted(sub)) for sub in test_list))
# print resultprint("The list after duplicate removal : " + str(res))

输出结果:

原始列表:[[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]]

去重后的列表:[(-1, 0, 1), (1, 3, 4), (1, 2, 3)]

您也可以使用 set() + map() + sorted()

# Python3 code to demonstrate# removing duplicate sublist # using set() + map() + sorted()
# initializing listtest_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1],                           [1, 2, 3], [3, 4, 1]]
# printing original listprint("The original list : " + str(test_list))
# using set() + map() + sorted()# removing duplicate sublistres = list(set(map(lambda i: tuple(sorted(i)), test_list)))
# print resultprint("The list after duplicate removal : " + str(res))

输出结果:

原始列表:[[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]]

去重后的列表:[(-1, 0, 1), (1, 3, 4), (1, 2, 3)]

本文完~

可以使用多方法Python列表进行去重。以下是几常见的方法: 1. 使用for循环和if语句创建一个新的列表,只添加不重复的元素。可以使用一个空列表来存储不重复的元素,然后遍历原始列表,检查每个元素是否已经存在于新列表。如果不存在,则将其添加到新列表。这方法可以保留原始列表的顺序。例如:\[1\] 2. 使用字典(dict)的键来去重。可以创建一个空字典,然后遍历原始列表,将每个元素作为字典的键,并将其值设置为任意非空值。由于字典的键是唯一的,重复的元素将被自动去重。最后,可以将字典的键转换为列表,以获取去重后的结果。这方法也可以保留原始列表的顺序。例如:\[2\] 3. 使用集合(set)来去重。可以使用set()函数创建一个无序不重复元素的集合,然后将原始列表作为参数传递给set()函数。集合会自动去除重复的元素。最后,可以将集合转换为列表,以获取去重后的结果。需要注意的是,集合是无序的,所以去重后的列表可能会改变元素的顺序。例如:\[3\] 以上是几常见的Python列表去重方法,你可以根据具体的需求选择适合的方法。 #### 引用[.reference_title] - *1* *3* [Python 列表(list)去重的几方式](https://blog.csdn.net/p1306252/article/details/119607065)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python对列表list去重的4实现方法](https://blog.csdn.net/zh6526157/article/details/122516733)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cheng-Dashi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值