[英]Remove duplicates from list of lists of tuples
我有一个很长的列表,看起来像这样:
triangles = [[(-4, 48, 52), (-4, 48, 52), (-4, 48, 53)],
[(-4, 48, 53), (-4, 48, 53), (-4, 48, 52)],
[(4, 48, 53), (4, 48, 52), (4, 48, 52)],
[(4, 48, 52), (4, 48, 53), (4, 48, 53)],
[(-4, 48, 52), (-4, 48, 52), (-4, 48, 53)],
[(-4, 48, 53), (-4, 48, 53), (-4, 48, 52)],
[(4, 48, 53), (4, 48, 52), (4, 48, 52)],
[(4, 48, 52), (4, 48, 53), (4, 48, 53)],
[(-4, 48, 52), (-4, 48, 52), (-4, 48, 53)],
[(-4, 48, 53), (-4, 48, 53), (-4, 48, 52)]]
它包含三角形角的 3 个坐标列表。 现在我需要删除所有重复的三角形。 只是做list(set(triangles))
是行不通的。 它抛出这个错误:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 96, in <module>
TypeError: unhashable type: 'list'
如何删除重复的三角形?
列表是不可散列的,因此将所有内容都设为元组:
list({tuple(sorted(x)) for x in triangles})
如果顶点的顺序不同,就会进行排序。 如果不应该删除不同的顺序顶点(或不存在),那么您可以摆脱排序并用map(tuple, triangles)
替换整个map
。
如果您希望各个元素再次成为列表,请使用列表推导来实现:
[list(x) for x in {tuple(sorted(x)) for x in triangles}]
如果您要查找的只是在整个列表中完全唯一的特定元组,那么您可以使用itertools.chain
将列表列表“展平”为单个迭代器以提供给set
:
>>> from itertools import chain
>>> list(set(chain(*triangles)))
[(-4, 48, 52), (4, 48, 52), (-4, 48, 53), (4, 48, 53)]
aplet 的答案是 go 的方式,但我会添加一个基本的方式。 由于您尝试使用 {},我假设重复的三角形是 2 个相同的子列表。
然后,您可以使用以下命令构建一个新的 2d 列表:
newList = []
for i in triangles:
if i not in newList:
newList.append(i)
如果我理解正确,您需要使元组列表在整个列表列表中是唯一的。 然后这是我的工作解决方案:
def remove_duplicates(list):
return [list(t) for t in (set(tuple(i) for i in lst))]
triangles = [[(-4, 48, 52), (-4, 48, 52), (-4, 48, 53)],
[(-4, 48, 53), (-4, 48, 53), (-4, 48, 52)],
[(4, 48, 53), (4, 48, 52), (4, 48, 52)],
[(4, 48, 52), (4, 48, 53), (4, 48, 53)],
[(-4, 48, 52), (-4, 48, 52), (-4, 48, 53)],
[(-4, 48, 53), (-4, 48, 53), (-4, 48, 52)],
[(4, 48, 53), (4, 48, 52), (4, 48, 52)],
[(4, 48, 52), (4, 48, 53), (4, 48, 53)],
[(-4, 48, 52), (-4, 48, 52), (-4, 48, 53)],
[(-4, 48, 53), (-4, 48, 53), (-4, 48, 52)]]
print(remove_duplicates(triangles))
output 是:
[[(-4, 48, 52), (-4, 48, 52), (-4, 48, 53)],
[(4, 48, 52), (4, 48, 53), (4, 48, 53)],
[(4, 48, 53), (4, 48, 52), (4, 48, 52)],
[(-4, 48, 53), (-4, 48, 53), (-4, 48, 52)]]
因此,从整个列表列表中删除了重复的元组列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.