Python 去除序列s中的重复元素

来源:互联网 发布:windows资源管理器在哪 编辑:程序博客网 时间:2024/06/05 10:13

http://www.cnblogs.com/moinmoin/archive/2011/09/26/python-remove-list-repeat-hash.html


1.在可hash的情况下使用set,时间复杂度为 O(n)

?
1
return list(set(s))

2.不可hash,但支持比较使用sort,时间复杂度为 O(nlogn)

?
1
2
3
4
5
6
7
t=list(s)
try:
    t.sort()
except TypeError:
    del t
else:
    return [xfor i,xin enumerate(t)if not ior t[i]!=t[i-1]]

3.前两者都不能的情况下利用in判断,时间复杂度为 O(n**2)

?
1
2
3
4
5
u=[]
for xin s:
    if xnot in u:
         u.append(x)
return u

原创粉丝点击