我对以下问题感到好奇:消除列表元素的连续重复,以及如何在Python中实现它。我想到的是:list = [1,1,1,1,1,1,2,3,4,4,5,1,2]i = 0while i < len(list)-1: if list[i] == list[i+1]: del list[i] else: i = i+1输出:[1, 2, 3, 4, 5, 1, 2]我猜没关系。所以我很好奇,想看看是否可以删除具有连续重复项的元素并获得以下输出:[2, 3, 5, 1, 2]为此,我这样做:list = [1,1,1,1,1,1,2,3,4,4,5,1,2]i = 0dupe = Falsewhile i < len(list)-1: if list[i] == list[i+1]: del list[i] dupe = True elif dupe: del list[i] dupe = False else: i += 1但是似乎有点笨拙而不是pythonic,您是否有任何更聪明/更优雅/更有效的方法来实现这一点?
3 回答

catspeake
TA贡献1111条经验 获得超0个赞
这是不依赖外部程序包的解决方案:
list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
L = list + [999] # append a unique dummy element to properly handle -1 index
[l for i, l in enumerate(L) if l != L[i - 1]][:-1] # drop the dummy element
然后我注意到,Ulf Aslak的类似解决方案更干净:)
添加回答
举报
0/150
提交
取消