Python删除for循环中的数组项

时间:2015-06-29 08:39:27

标签: python arrays

我试图根据彼此的距离删除数组中的一些项目。

我在带有元组的数组中有 104 项:

points = [(910, 28), (914, 29), (919, 30), (915, 32), (766, 73), (777, 75), (768, 80), (1227, 117), (1224, 119), (1228, 120), (1224, 121), (1228, 122), (1221, 124), (1218, 126), (486, 147), (482, 150), (474, 153), (905, 182), (908, 184), (904, 186), (901, 187), (913, 188), (909, 190), (903, 193), (187, 213), (186, 214), (189, 215), (611, 262), (617, 264), (619, 265), (610, 268), (1231, 272), (1228, 274), (1228, 276), (1232, 278), (1223, 282), (486, 306), (477, 309), (463, 312), (470, 313), (486, 315), (473, 319), (764, 376), (773, 379), (770, 383), (795, 386), (778, 390), (631, 412), (626, 414), (624, 416), (626, 418), (1218, 434), (1217, 435), (1218, 436), (1219, 437), (1220, 438), (1222, 439), (1225, 440), (1226, 442), (480, 460), (478, 463), (1071, 466), (1062, 468), (1067, 469), (1072, 470), (339, 485), (343, 487), (345, 489), (346, 490), (350, 492), (343, 495), (352, 497), (930, 505), (929, 508), (929, 513), (199, 535), (197, 537), (203, 539), (201, 542), (771, 547), (774, 547), (773, 548), (772, 549), (776, 549), (776, 550), (629, 576), (628, 579), (631, 580), (625, 583), (1237, 586), (1218, 590), (1226, 593), (1223, 595), (1227, 599), (639, 732), (643, 733), (643, 734), (204, 875), (209, 877), (210, 879), (210, 880), (210, 882), (210, 884), (204, 887)]

我的代码如下:

print len(points)
w = 152
h = 157
for pt in points:
    for fpt in points:
        if pt == fpt:
            continue
        else:
            distX = abs(pt[0] - fpt[0])
            distY = abs(pt[1] - fpt[1])
            dist = distX + distY
            if distX < w / 2 and distY < h / 2:
                points.remove(fpt)

print len(points)

当我运行它时,它会移除大量项目并且只留下 33 ,但它不正确。如果我再次运行它会留下正确的数字 22

我确信我做错了什么,有人能帮我找到并纠正我的错误吗?

1 个答案:

答案 0 :(得分:2)

在迭代列表时删除列表项不是一种好习惯。 例如,

if points has only 3 elements [a, b, c], 
a is adjacent to b, 
b is adjacent to c, 
but a is not adjacent to c, 
Correct result is [a] after the algorithm runs. But with your algorithm,
after the first iteration, b is removed; points = [a, c]
c can never be removed, since a and c are not adjacent.

您正在寻找的是Union-find-set,这是一个实现: http://code.activestate.com/recipes/215912-union-find-data-structure/

这是一个更天真的Union-Find实现,供您参考: A set union find algorithm