如何让列表只包含Python中的独特元素？

``````def f(seq): # Order preserving
''' Modified version of Dave Kirby solution '''
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
``````

``````In [1]: 0 not in [1,2,3] and not print('add')
Out[1]: True
``````

``````In [3]: type(seen.add(10))
Out[3]: <type 'NoneType'>
``````

`not None == True` ，但：

``````In [2]: 1 not in [1,2,3] and not print('add')
Out[2]: False
``````

``````def f(seq, idfun=None): # Order preserving
return list(_f(seq, idfun))

def _f(seq, idfun=None):
''' Originally proposed by Andrew Dalke '''
seen = set()
if idfun is None:
for x in seq:
if x not in seen:
yield x
else:
for x in seq:
x = idfun(x)
if x not in seen:
yield x
``````

``````def f(seq): # Not order preserving
return list(set(seq))
``````
python

``````l = [1, 1, 2, 2, 3]
result = list()
map(lambda x: not x in result and result.append(x), l)
result
# [1, 2, 3]
``````

``````>>> mylist = [3, 2, 1, 3, 4, 4, 4, 5, 5, 3]

>>> {x:1 for x in mylist}.keys()
[1, 2, 3, 4, 5]
``````

``````>>> from collections import OrderedDict

>>> OrderedDict( (x,1) for x in mylist ).keys()
[3, 2, 1, 4, 5]
``````

``````d = {}
for x in mylist:
d[x] = 1
mylist = list(d.keys())
``````

Python中的集合的特征是集合中的数据项是无序的，并且不允许重复。 如果您尝试将数据项添加到已包含数据项的集合中，则Python将忽略它。

``````>>> l = ['a', 'a', 'bb', 'b', 'c', 'c', '10', '10', '8','8', 10, 10, 6, 10, 11.2, 11.2, 11, 11]
>>> distinct_l = set(l)
>>> print(distinct_l)
set(['a', '10', 'c', 'b', 6, 'bb', 10, 11, 11.2, '8'])
``````

python