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

['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中快速获取其中一个的总结。

鉴于

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

相同顺序唯一的列表只使用一个列表压缩。

> my_list = [1, 2, 1, 3, 2, 4, 3, 5, 4, 3, 2, 3, 1]
> unique_list = [
>    e
>    for i, e in enumerate(my_list)
>    if my_list.index(e) == i
> ]
> unique_list
[1, 2, 3, 4, 5]

enumates以元组的形式给出索引I和元素e。

my_list。index返回e的第一个索引。如果第一个索引不是i,则当前迭代的e不是列表中的第一个e。

Edit

我应该指出,就性能而言,这不是一种好方法。这只是一种仅使用列表压缩来实现它的方法。

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

list(set(my_not_unique_list))

简单而简短。

我知道这是一个老问题,但我有一个独特的解决方案:类继承!:

class UniqueList(list):
    def appendunique(self,item):
        if item not in self:
            self.append(item)
            return True
        return False

然后,如果你想唯一地将项目附加到列表中,你只需在UniqueList上调用appendunique。因为它继承自一个列表,所以它基本上就像一个列表,所以你可以使用index()等函数。因为它返回true或false,所以可以知道追加是成功(唯一项)还是失败(已经在列表中)。

要从列表中获得唯一的项列表,请使用for循环将项追加到UniqueList(然后复制到列表中)。

示例用法代码:

unique = UniqueList()

for each in [1,2,2,3,3,4]:
    if unique.appendunique(each):
        print 'Uniquely appended ' + str(each)
    else:
        print 'Already contains ' + str(each)

打印:

Uniquely appended 1
Uniquely appended 2
Already contains 2
Uniquely appended 3
Already contains 3
Uniquely appended 4

复制到列表:

unique = UniqueList()

for each in [1,2,2,3,3,4]:
    unique.appendunique(each)

newlist = unique[:]
print newlist

打印:

[1, 2, 3, 4]