1.在可hash的情况下使用set,时间复杂度为 O(n)
return list(set(s))
2.不可hash,但支持比较使用sort,时间复杂度为 O(nlogn)
t=list(s) try: t.sort() except TypeError: del t else: return [x for i,x in enumerate(t) if not i or t[i]!=t[i-1]]
3.前两者都不能的情况下利用in判断,时间复杂度为 O(n**2)
u=[] for x in s: if x not in u: u.append(x)
return u
enumerate()函数使用说明:
enumerate( sequence [, start=0 ])
Return an enumerate object. sequence must be a sequence, an iterator, or
some other object which supports iteration. The next() method of the
iterator returned by enumerate() returns a tuple containing a count
(from start which defaults to 0) and the values obtained from iterating oversequence:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')