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

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

有更好的解决方案吗?


当前回答

试试这个函数,它与你的代码类似,但它是一个动态范围。

def unique(a):

    k=0
    while k < len(a):
        if a[k] in a[k+1:]:
            a.pop(k)
        else:
            k=k+1



    return a

其他回答

通过使用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'])

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

mylist = list(set(mylist))

使用set去重复列表,返回为列表

def get_unique_list(lst):
        if isinstance(lst,list):
            return list(set(lst))
def setlist(lst=[]):
   return list(set(lst))

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

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