说,我有一个如下列表:
if(i < smallIndex)
我想删除重复的连续元组。所以在上面的例子中,它应该返回:
$sql=mysql_query("SELECT * FROM subjects");
答案 0 :(得分:10)
您可以使用itertools.groupby
:
from itertools import groupby
x = [(2, 1), (1, 0), (1, 0), (1, 0), (2, 1), (2, 1)]
x_grouped = [i for i, j in groupby(x)]
# [(2, 1), (1, 0), (2, 1)]
答案 1 :(得分:6)
您可以使用仅生成与前一个元素不相等的元素的生成器:
def filter_consecutive_duplicates(it):
prev = object() # sentinel object, won't be equal to anything else
for elem in it:
if elem != prev:
yield elem
prev = elem
演示:
>>> list(filter_consecutive_duplicates([(2, 1), (1, 0), (1, 0),(1,0),(2,1), (2, 1)]))
[(2, 1), (1, 0), (2, 1)]
答案 2 :(得分:1)
a=[(2, 1), (1, 0), (1, 0), (1,0), (2,1), (2, 1)]
a=[elem for count,elem in enumerate(a) if elem!=a[count-1] or count==0]
这个列表理解怎么样