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

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

集合——唯一元素的无序集合。元素列表可以传递给set的构造函数。传递带有重复元素的list,我们得到带有唯一元素的set然后将它转换回带有唯一元素的list。我对性能和内存开销没有什么可说的,但我希望,对于小列表来说,这不是那么重要。

list(set(my_not_unique_list))

简单而简短。

对于长数组

s = np.empty(len(var))

s[:] = np.nan

for  x in  set(var):

    x_positions = np.where(var==x)

    s[x_positions[0][0]]=x


sorted_var=s[~np.isnan(s)]

Python列表:

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

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

>>> b = set(a)
>>> print(b)
{'b', 'c', 'd', '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'])