unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3]) == [1,2,3]
def unique_in_order(iterable):
q = list(iterable)
i = 1
while i < len(q):
if q[i-1] == q[i]:
q.pop(i)
else:
i += 1
return q
刚开始写的
def unique_in_order(iterable):
q = list(iterable)
for i in range(1, len(q)):
if q[i-1] == q[i]:
q.pop(i)
return q
有错误:用于迭代的序列只有一次初始机会。
论坛中其他大神的解答:
from itertools import groupby
def unique_in_order(iterable):
return [x for x, _ in groupby(iterable)]
def unique_in_order(iterable):
return [z for i, z in enumerate(iterable) if i == 0 or z != iterable[i-1]]
网友评论