通过将其元素与 Python 中所有其他子列表中的元素进行比较来删除子列表
Removing sub list by comparing its elements with elements in all other sub lists in Python
我将线段的开始和结束坐标与一些属性一起存储在列表列表中,形式为。
我想从我的主列表中删除每个子列表,其中一对坐标 (x1 y1 , x2 y2) 已经存在于我的列表中但相反 (x2 y2 , x1 y1)
我的代码是:
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)
这段代码导致删除了一些我想要的元素(虽然不是全部)和一些不应删除的元素。知道我可能遗漏了什么吗?
在对初始代码进行少量调整并修复错误后,这段代码给出了正确的输出:
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]])
我将线段的开始和结束坐标与一些属性一起存储在列表列表中,形式为。
我想从我的主列表中删除每个子列表,其中一对坐标 (x1 y1 , x2 y2) 已经存在于我的列表中但相反 (x2 y2 , x1 y1)
我的代码是:
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)
这段代码导致删除了一些我想要的元素(虽然不是全部)和一些不应删除的元素。知道我可能遗漏了什么吗?
在对初始代码进行少量调整并修复错误后,这段代码给出了正确的输出:
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]])