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

['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)

有更好的解决方案吗?


当前回答

除了前面的答案,你可以把你的列表转换成集合,你也可以用这种方式

mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenadnow']
mylist = [i for i in set(mylist)]

输出将是

[u'nowplaying', u'job', u'debate', u'PBS', u'thenadnow']

尽管秩序将不复存在。

另一个更简单的答案是(不使用集合)

>>> t = [v for i,v in enumerate(mylist) if mylist.index(v) == i]
[u'nowplaying', u'PBS', u'job', u'debate', u'thenadnow']

其他回答

要从列表中获得唯一的值,请使用下面的代码:

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

重要的是: 如果列表中的任何项都不是可哈希的,上述方法将不起作用,这是可变类型的情况,例如list或dict。

trends = [{'super':u'nowplaying'}, u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
output = set(trends)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: unhashable type: 'dict'

这意味着你必须确保趋势列表总是只包含可哈希项,否则你必须使用更复杂的代码:

from copy import deepcopy

try:
    trends = [{'super':u'nowplaying'}, [u'PBS',], [u'PBS',], u'nowplaying', u'job', u'debate', u'thenandnow', {'super':u'nowplaying'}]
    output = set(trends)
    output = list(output)
except TypeError:
    trends_copy = deepcopy(trends)
    while trends_copy:
        trend = trends_copy.pop()
        if trends_copy.count(trend) == 0:
            output.append(trend)
print output

如果你在你的代码中使用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而不进行排序。

Set可以帮助您从列表中过滤出重复的元素。它适用于str, int或tuple元素,但如果您的列表包含dict或其他列表元素,那么您将以TypeError异常结束。

下面是一个通用的保序解决方案来处理一些(不是所有)不可哈希类型:

def unique_elements(iterable):
    seen = set()
    result = []
    for element in iterable:
        hashed = element
        if isinstance(element, dict):
            hashed = tuple(sorted(element.iteritems()))
        elif isinstance(element, list):
            hashed = tuple(element)
        if hashed not in seen:
            result.append(element)
            seen.add(hashed)
    return result

你可以使用集合。为了明确起见,我正在解释列表和集合之间的区别。 集合是唯一元素的无序集合。列表是元素的有序集合。 所以,

    unicode_list=[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job',u'debate', u'thenandnow']
    list_unique=list(set(unicode_list))
    print list_unique
[u'nowplaying', u'job', u'debate', u'PBS', u'thenandnow']

但是:不要使用list/set来命名变量。它会导致错误: 在上面的例子中,不是用list代替unicode_list。

list=[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job',u'debate', u'thenandnow']
        list_unique=list(set(list))
        print list_unique
    list_unique=list(set(list))
TypeError: 'list' object is not callable

我很惊讶,到目前为止还没有人给出一个直接的维持秩序的答案:

def unique(sequence):
    """Generate unique items from sequence in the order of first occurrence."""
    seen = set()
    for value in sequence:
        if value in seen:
            continue

        seen.add(value)

        yield value

它将生成值,因此它不仅仅适用于列表,例如unique(range(10))。要获得一个列表,只需调用list(unique(sequence)),如下所示:

>>> list(unique([u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']))
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']

它要求每一项都是可哈希的,而不仅仅是可比较的,但Python中的大多数东西都是可哈希的,它是O(n)而不是O(n²),所以对于长列表来说很好。