Python 删除列表中的重复数据

有很多方法可以从Python列表中删除重复。

从列表中删除重复

Python 列表可以包含重复元素,让我们看看如何以不同的方式删除重复元素的例子。

1、使用临时清单

这是从列表中删除重复元素的 brute force 方法,我们将创建临时列表,并仅在不存在的情况下添加元素。

 1ints_list = [1, 2, 3, 4, 3, 2]
 2
 3temp = []
 4
 5for x in ints_list:
 6    if x not in temp:
 7        temp.append(x)
 8
 9ints_list = temp
10
11print(f'Updated List after removing duplicates = {temp}')

** 输出**: 删除重复列表后更新列表 = [1, 2, 3, 4] ** 推荐阅读**: Python f-strings

二、函数( )

我们可以使用内置的 set() 函数将列表转换为集合,然后使用 list() 函数将其转换回列表。

1ints_list = [1, 2, 3, 4, 3, 2]
2
3ints_list1 = list(set(ints_list))
4print(ints_list1)  # [1, 2, 3, 4]

列表元素作为字典密钥

我们知道字典密钥是独一无二的. dict 类具有 fromkeys() 函数,它接受可迭代的函数来创建从可迭代的密钥的字典。

1ints_list = [1, 2, 3, 4, 3, 2]
2
3ints_list2 = list(dict.fromkeys(ints_list))
4print(ints_list2)  # [1, 2, 3, 4]

列表数() 函数 - 不推荐

列表 count() 方法返回值的发生次数,我们可以使用 remove() 方法来从列表中删除重复元素。

1ints_list = [1, 2, 3, 4, 3, 2]
2
3for x in ints_list:
4    if ints_list.count(x) > 1:
5        ints_list.remove(x)
6print(ints_list)  # [1, 2, 3, 4]

** 注意:如下评论所指出,在从同一迭代器中删除元素时,不建议使用 count() 函数,因为这可能会导致不必要的结果。

1values = [87, 94, 45, 94, 94, 41, 65, 94, 41, 99, 94, 94, 94]
2
3for x in values:
4    if values.count(x) > 1:
5        values.remove(x)
6print(values)  # [87, 45, 65, 41, 99, 94, 94] - 94 is still present twice

五、理解清单

我们可以使用列表理解来创建一个可迭代的列表,这种技术与使用临时列表和 for loop相同,以删除重复元素,但它会减少代码的行数。

1int_list = [1, 2, 3, 4, 3, 2]
2temp = []
3[temp.append(x) for x in ints_list if x not in temp]
4print(temp)  # [1, 2, 3, 4]

从列表中删除重复的最佳方法

但是,如果您必须从列表中删除重复值,那么我会更喜欢 count() 函数,因为它不会创建另一个临时集或列表对象。

Published At
Categories with 技术
Tagged with
comments powered by Disqus