遍历去重
>>> lst1 = [2, 1, 3, 4, 1]
>>> temp = []
>>> for item in lst1:
if not item in temp:
temp.append(item)
>>> print(temp)
[2, 1, 3, 4]
推导式去重
>>> lst1 = [2, 1, 3, 4, 1]
>>> temp = []
>>> [temp.append(i) for i in lst1 if not i in temp]
[None, None, None, None]
>>> print(temp)
[2, 1, 3, 4]
双指针去重
i,j两个指针分别指向第i个和第i+1个元素,比较,相等j后移,直到不等将第i个元素加到新列表。j赋给i,开始下一次循环即可。
def uniqList03(data=None):
data = sorted(data)
newdata = []
stop = len(data) - 1
i = 0
while i <= stop:
j = i + 1
if i == stop:
newdata.append(data[i])
i += 1
else:
if data[i] == data[j]:
while j <= stop and data[i] == data[j]:
j += 1
newdata.append(data[i])
i = j
return newdata