从列表列表中获取独特的项目?
我有一个如下所示的列表列表:
animal_groups = [['fox','monkey', 'zebra'], ['snake','elephant', 'donkey'],['beetle', 'mole', 'mouse'],['fox','monkey', 'zebra']]
删除重复列表的最佳方法是什么?使用上面的示例,我正在寻找会产生以下结果的代码:
uniq_animal_groups = [['fox','monkey', 'zebra'], ['snake','elephant', 'donkey'],['beetle', 'mole', 'mouse']]
我首先想到我可以使用 set()
,但这似乎不适用于列表列表。我还看到了一个使用 itertools 的示例,但代码对我来说并不完全清楚。感谢您的帮助!
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']]
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就可以了,尽管你最终会得到一组元组而不是一组列表。 (当然,您可以将其转换回列表列表,但除非有特定原因这样做,否则为什么要麻烦呢?)
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?)
将列表转换为元组,然后可以将它们放入集合中。
本质上:
如果您希望结果是列表的列表,请尝试:
或:
Convert the lists to tuples, and then you can put them into a set.
Essentially:
If you prefer the result to be a list of lists, try:
or:
当您不关心内部列表的排序时,请首先将所有内容转换为集合:
When you don't care about the sorting of internal lists, convert everything to sets first: