删除列表中的反向重复的方式 [英] Pythonic way of removing reversed duplicates in list

查看:82
本文介绍了删除列表中的反向重复的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组对:

[0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]

想要删除任何重复的地方,其中

and I want to remove any duplicates where

[a,b] == [b,a]

所以我们最终只是

[0, 1], [0, 4], [1, 4]

内在&外部循环检查反向对,并附加到列表,如果不是这样,但我相信有一个更加Pythonic的方式来实现相同的结果。

I can do an inner & outer loop checking for the reverse pair and append to a list if that's not the case, but I'm sure there's a more Pythonic way of achieving the same results.

推荐答案

如果您需要保留列表中元素的顺序,则可以使用 排序 功能并设置理解与 map 这样:

If you need to preserve the order of the elements in the list then, you can use a the sorted function and set comprehension with map like this:

lst = [0, 1], [0, 4], [1, 0], [1, 4], [4, 0], [4, 1]
data = {tuple(item) for item in map(sorted, lst)}
# {(0, 1), (0, 4), (1, 4)}

或简单地没有地图像这样:

data = {tuple(sorted(item)) for item in lst}

另一种方法是使用 frozenset 如图所示这里,但请注意,只有您的列表中有不同的元素,这只能工作。因为像设置 frozenset 总是包含唯一的值。所以你将在你的子列表中丢失唯一的值(丢失数据),这可能不是你想要的。

Another way is to use a frozenset as shown here however note that this only work if you have distinct elements in your list. Because like set, frozenset always contains unique values. So you will end up with unique value in your sublist(lose data) which may not be what you want.

要输出一个列表,你可以随时使用 list(map(list,result))其中result是一组仅在Python-3.0或更新版本中的元组。

To output a list, you can always use list(map(list, result)) where result is a set of tuple only in Python-3.0 or newer.

这篇关于删除列表中的反向重复的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆