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

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

其他回答

首先正确地声明列表,用逗号分隔。您可以通过将列表转换为集合来获得唯一的值。

mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)

如果你进一步将其作为列表使用,你应该通过以下操作将其转换回列表:

mynewlist = list(myset)

另一种可能,可能更快的是,从一开始就使用集合,而不是列表。那么你的代码应该是:

output = set()
for x in trends:
    output.add(x)
print(output)

正如已经指出的那样,集合不保持原来的顺序。如果你需要它,你应该寻找一个有序集实现(更多信息请参阅这个问题)。

删除重复项的选项可能包括以下通用数据结构:

集合:无序的,唯一的元素 有序集:有序的、唯一的元素

下面是关于如何在Python中快速获取其中一个的总结。

鉴于

from collections import OrderedDict


seq = [u"nowplaying", u"PBS", u"PBS", u"nowplaying", u"job", u"debate", u"thenandnow"]

Code

选项1 -一组(无序):

list(set(seq))
# ['thenandnow', 'PBS', 'debate', 'job', 'nowplaying']
    

Python没有有序集,但这里有一些模拟有序集的方法。

选项2 -一个OrderedDict(插入顺序):

list(OrderedDict.fromkeys(seq))
# ['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']

选项3 -字典(插入顺序),Python 3.6+中的默认值。在这篇文章中可以看到更多细节:

list(dict.fromkeys(seq))
# ['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']

注意:列出的元素必须是可哈希的。在这篇博客文章中查看后一个示例的详细信息。此外,请参阅R. Hettinger关于相同技术的帖子;保序字典是从他早期的一个实现扩展而来的。参见更多关于总排序的信息。

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

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

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

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

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