我想从下面的列表中获得唯一的值:

['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']

我需要的输出是:

['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']

这段代码工作:

output = []
for x in trends:
    if x not in output:
        output.append(x)
print(output)

有更好的解决方案吗?


当前回答

Set是一个无序且唯一元素的集合。所以,你可以使用set来获得一个唯一的列表:

unique_list = list(set([u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']))

其他回答

为了与我使用的类型保持一致:

mylist = list(set(mylist))

如果你在你的代码中使用numpy(对于大量的数据来说,这可能是一个很好的选择),检查numpy.unique:

>>> import numpy as np
>>> wordsList = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
>>> np.unique(wordsList)
array([u'PBS', u'debate', u'job', u'nowplaying', u'thenandnow'], 
      dtype='<U10')

(http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html)

可以看到,numpy不仅支持数值数据,还支持字符串数组。当然,结果是一个numpy数组,但这并不重要,因为它仍然表现得像一个序列:

>>> for word in np.unique(wordsList):
...     print word
... 
PBS
debate
job
nowplaying
thenandnow

如果你真的想要返回一个普通的python列表,你总是可以调用list()。

但是,结果是自动排序的,从上面的代码片段可以看出。如果需要保留列表顺序,则签出numpy unique而不进行排序。

作为奖励,Counter是一种获得唯一值和每个值的计数的简单方法:

from collections import Counter
l = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
c = Counter(l)

Python列表:

>>> a = ['a', 'b', 'c', 'd', 'b']

要获得唯一的项,只需将其转换为一个集合(如果需要,您可以将其转换回列表):

>>> b = set(a)
>>> print(b)
{'b', 'c', 'd', 'a'}

Set是一个无序且唯一元素的集合。所以,你可以使用set来获得一个唯一的列表:

unique_list = list(set([u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']))