本文介绍了在保持顺序的同时删除二维数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现有很多线程可以删除数组中的重复项,但对于我的特定用例却没有。我有一个二维列表,我需要从中删除重复项,但是我必须保持原始顺序
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%']]
感谢任何帮助
推荐答案
使用来跟踪可见项目:
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]))
>>>
这篇关于在保持顺序的同时删除二维数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!