在保持顺序的同时删除二维数组中的重复项

问题描述:

我发现有很多线程可以删除数组中的重复项,但对于我的特定用例却没有。我有一个二维列表,我需要从中删除重复项,但是我必须保持原始顺序

I have found a lot of threads on removing duplicates in arrays but none for my specific use-case. I have a two-dimensional list that I need to remove duplicates from however I must maintain the original sequence

mylist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

我只需要删除重复项

newlist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

感谢任何帮助

使用 set 来跟踪可见项目:

Using set to keep track of seen items:

>>> mylist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]
>>> seen = set()
>>> newlist = []
>>> for item in mylist:
...     t = tuple(item)
...     if t not in seen:
...         newlist.append(item)
...         seen.add(t)
...
>>> newlist
[['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]

注意

您需要将列表转换为元组(列表不可散列);

You need to convert a list to tuple (list is not hashable); can't add a list to set.

>>> seen = set()
>>> seen.add([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> seen.add(tuple([1,2]))
>>>