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

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

有更好的解决方案吗?


当前回答

如果你想从列表中获取唯一的元素并保持它们的原始顺序,那么你可以使用Python标准库中的OrderedDict数据结构:

from collections import OrderedDict

def keep_unique(elements):
    return list(OrderedDict.fromkeys(elements).keys())

elements = [2, 1, 4, 2, 1, 1, 5, 3, 1, 1]
required_output = [2, 1, 4, 5, 3]

assert keep_unique(elements) == required_output

事实上,如果你使用的是Python≥3.6,你可以使用普通dict:

def keep_unique(elements):
    return list(dict.fromkeys(elements).keys())

在引入字典的“紧凑”表示之后,这成为可能。点击这里查看。尽管这“被认为是一个实现细节,不应该依赖”。

其他回答

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

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

通过使用Python Dictionary的基本属性:

inp=[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
d={i for i in inp}
print d

输出将是:

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

在代码开始时,只需将输出列表声明为空:output=[] 您可以使用以下代码代替您的代码trends=list(set(trends))

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

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']

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

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²),所以对于长列表来说很好。