简体   繁体   中英

Removing sub list by comparing its elements with elements in all other sub lists in Python

I am storing the start and end coordinates of line segments together with some attributes in a list of lists with the form.

I want to remove from my main list each sub list where the pair of coordinates (x1 y1 , x2 y2) already exist in my list but reversed (x2 y2 , x1 y1)

My code is:

lines=[[(x1, y1), (x2, y2), id1, id2],[(x2, y2), (x1, y1), id2, id1]] #random example 
lns=[ [l[0], l[1]] for l in lines] #make a list only with the node coordinate pairs
for line in lines:
if [line[1],line[0]] in lns: 
    lines.remove(line) 

This code results in removing some of the elements that I want (not all of them though) and some that shouldn't be removed. Any idea what I may be missing?

With few adjustments in the initial code and after fixing the bug this code gives the correct output:

lines=[[(x1, y1), (x2, y2), id1, id2],[(x2, y2), (x1, y1), id2, id1]]
for line in lines:
    if [line[1],line[0], line[3],line[2]] in lns: 
         lines.remove([line[1],line[0], line[3],line[2]]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM