問題描述
我有一個如下所示的列表:
I have a list of lists that looks like this:
animal_groups = [['fox','monkey', 'zebra'], ['snake','elephant', 'donkey'],['beetle', 'mole', 'mouse'],['fox','monkey', 'zebra']]
刪除重復列表的最佳方法是什么?使用上面的例子,我正在尋找可以產生這個的代碼:
What is the best to remove duplicate lists? Using the above example, I am looking for code that would produce this:
uniq_animal_groups = [['fox','monkey', 'zebra'], ['snake','elephant', 'donkey'],['beetle', 'mole', 'mouse']]
我最初認為我可以使用 set()
,但這似乎不適用于列表列表.我還看到了一個使用 itertools
的示例,但代碼對我來說并不完全清楚.感謝您的幫助!
I first thought I could use set()
, but this doesn't appear to work on a list of lists. I also saw an example using itertools
, but the code was not entirely clear to me. Thanks for the help!
推薦答案
uniq_animal_groups = set(map(tuple, animal_groups))
可以解決問題,盡管您最終會得到一組元組而不是一組列表.(當然您可以將其轉換回列表列表,但除非有特定原因,否則為什么要這樣做?)
will do the trick, though you will end up with a set of tuples instead of a set of lists. (Of course you could convert this back to a list of lists, but unless there is a specific reason to do so, why bother?)
這篇關于從列表列表中獲取唯一項目?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!