def drop_cycle(edge, max_length=20):
"""
删除列表中形成的小闭环
@edge: 原始顶点id
@max_length: 容许闭环的最小长度
return: 输出删除小闭环后的列表
"""
drop_list = []
drop_count = 0
for i, item in enumerate(edge):
if item not in drop_list:
drop_list.append(item)
else:
last_index = len(drop_list) - 1 - drop_list[::-1].index(item)
if i - last_index - drop_count < max_length:
drop_count += len(drop_list[last_index:])
drop_list = drop_list[:last_index+1]
else:
drop_list.append(item)
edge = np.asarray(drop_list)
# TODO 去掉首尾构成的闭环 如: [956 1035 1538 ...... 2028 1035 952 956] ==> 1035->952->956->1035
return edge
Test
a = [2, 3, 1, 2, 5, 8, 1, 6, 1, 2, 1, 3, 4, 1, 2]
print(drop_cycle(a, 3)) # [2 3 1 2 5 8 1 3 4 1 2]