簡體   English   中英

從元組列表中刪除重復項

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM