嘿,我有一个列表,我想删除列表中的循环。例如,如果一个元素已经在列表中,我想删除这个重复的元素之间的所有元素。例如:
a=[(4,4),(5,6),(7,7),(7,6),(4,4),(8,8),(9,9)]
我想得到与此类似的东西:
a [(4,4),(8,8),(9,9)]
我怎样才能得到这个?
谢谢
a = [(4,4),(5,6),(7,7),(7,6),(4,4),(8,8),(9,9)]
b = []
for e in a:
if e in b:
b[b.index(e)+1:] = []
else:
b.append(e)
# b == [(4, 4), (8, 8), (9, 9)]
#! /usr/bin/python3.2
while True:
loops = sorted ( ( (x [0], y [0] ) for x, y in [ (x, y) for x in enumerate (a) for y in enumerate (a) ] if x [0] < y [0] and x [1] == y [1] ), key = lambda x: x [0] - x [1])
if loops: a = a [:loops [0] [0] ] + a [loops [0] [1]:]
else: break
这应该删除所有循环,从(其中一个)最长的循环开始,以防相交(重叠)循环。