我有一个名为lt。
的元组列表lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
我想从列表中删除所有连续的重复元组。结果应如下所示。
mainList = [(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
答案 0 :(得分:5)
使用pairwise()
function from the itertools
reception section:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
mainList = [curr for curr, next in pairwise(lt) if curr != next]
这为您提供了一个删除了所有连续元组的新列表。您还可以使用itertools.groupby()
function和默认身份密钥:
from itertools import groupby
mainList = [k for k, g in groupby(lt)]
演示:
>>> from itertools import tee, groupby
>>> lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
>>> def pairwise(iterable):
... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
... a, b = tee(iterable)
... next(b, None)
... return zip(a, b)
...
>>> [curr for curr, next in pairwise(lt) if curr != next]
[(1, 2), (2, 3), (3, 4), (5, 6)]
>>> [k for k, g in groupby(lt)]
[(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
答案 1 :(得分:2)
lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
mainList = []
for t in lt:
if len(mainList) == 0:
mainList.append(t)
else:
if mainList[-1] != t:
mainList.append(t)
print(mainList)
<强> RESULT 强>
[(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
答案 2 :(得分:1)
错综复杂的列表理解怎么样?
[v for i, v in enumerate(lt) if i == o or v != lt[i-1]]
答案 3 :(得分:-1)
您可以尝试创建新列表,并将元素添加到该列表中。如果元素已经在新列表中,请不要添加它。
lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
newlt = [lt[0]]
for item in range(len(lt)):
if item == 0:
continue
elif lt[item] == lt[item - 1]:
continue
else:
newlt.append(lt[item])
print(newlt)
[(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
编辑:新解决方案,这应该工作。它显然非常基础。