从列表列表中获取独特的项目?

发布于 2024-11-27 20:04:44 字数 457 浏览 1 评论 0原文

我有一个如下所示的列表列表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

木槿暧夏七纪年 2024-12-04 20:04:45
uniq_animal_groups = set(map(tuple, animal_groups))

就可以了,尽管你最终会得到一组元组而不是一组列表。 (当然,您可以将其转换回列表列表,但除非有特定原因这样做,否则为什么要麻烦呢?)

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?)

心碎的声音 2024-12-04 20:04:45

将列表转换为元组,然后可以将它们放入集合中。

本质上:

uniq_animal_groups = set(map(tuple, animal_groups))

如果您希望结果是列表的列表,请尝试:

uniq_animal_groups = [list(t) for t in set(map(tuple, animal_groups))]

或:

uniq_animal_groups = map(list, set(map(tuple, animal_groups)))

Convert the lists to tuples, and then you can put them into a set.

Essentially:

uniq_animal_groups = set(map(tuple, animal_groups))

If you prefer the result to be a list of lists, try:

uniq_animal_groups = [list(t) for t in set(map(tuple, animal_groups))]

or:

uniq_animal_groups = map(list, set(map(tuple, animal_groups)))
风柔一江水 2024-12-04 20:04:45

当您不关心内部列表的排序时,请首先将所有内容转换为集合:

uniq_animal_groups  = map(list, set(map(tuple, map(set, animal_groups))))

When you don't care about the sorting of internal lists, convert everything to sets first:

uniq_animal_groups  = map(list, set(map(tuple, map(set, animal_groups))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文