Pythonic way of removing reversed duplicates in list(删除列表中反向重复项的 Pythonic 方法)
问题描述
我有一个配对列表:
[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.
推荐答案
如果需要保留列表中元素的顺序的话,可以使用sorted
函数并使用 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)}
或者干脆没有像这样的map
:
or simply without map
like this:
data = {tuple(sorted(item)) for item in lst}
另一种方法是使用 frozenset
,如 here 所示,但请注意,这仅在以下情况下有效您的列表中有不同的元素.因为像 set
一样,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.
这篇关于删除列表中反向重复项的 Pythonic 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:删除列表中反向重复项的 Pythonic 方法


- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 沿轴计算直方图 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01