删除列表中的重复项 [英] Removing duplicates in lists
问题描述
很多我需要编写一个程序来检查一个列表是否有任何重复的,如果它删除它们,并返回一个没有被重复/删除的项目的新列表。这是我所说的,但老实说,我不知道该怎么做。
Pretty much I need to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that werent duplicated/removed. This is what I have but to be honest I do not know what to do.
def remove_duplicates():
t = ['a', 'b', 'c', 'd']
t2 = ['a', 'c', 'd']
for t in t2:
t.append(t.remove())
return t
推荐答案
The common approach to get a unique collection of items is to use a set
. Sets are unordered collections of distinct objects. To create a set from any iterable, you can simply pass it to the built-in set()
function. If you later need a real list again, you can similarly pass the set to the list()
function.
以下示例应涵盖您尝试执行的任何操作: / p>
The following example should cover whatever you are trying to do:
>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1, 2, 3]
>>> list(set(t) - set(s))
[8, 5, 6, 7]
从示例结果可以看出,原始顺序不被维护。如上所述,集合本身是无序集合,因此订单丢失。将集合转换为列表时,将创建任意顺序。
As you can see from the example result, the original order is not maintained. As mentioned above, sets themselves are unordered collections, so the order is lost. When converting a set back to a list, an arbitrary order is created.
如果订单对您很重要,则必须使用其他机制。 此问题更详细地介绍了该主题。
If order is important to you, then you will have to use a different mechanism. This question covers that topic in more detail.
这篇关于删除列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!