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

['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 getUnique(self):
    notunique = self.readLines()
    unique = []
    for line in notunique: # Loop over content
        append = True # Will be set to false if line matches existing line
        for existing in unique:
            if line == existing: # Line exists ? do not append and go to the next line
                append = False
                break # Already know file is unique, break loop
        if append: unique.append(line) # Line not found? add to list
    return unique

编辑: 使用字典键来检查是否存在可能会更有效,而不是对每行进行整个文件循环,我不会对大集使用我的解决方案。

其他回答

首先,你给出的例子不是一个有效的列表。

example_list = [u'nowplaying',u'PBS', u'PBS', u'nowplaying', u'job', u'debate',u'thenandnow']

假设以上是示例列表。然后,您可以使用下面的配方来给出itertools示例文档,该文档可以返回唯一的值,并按照您的要求保留顺序。这里的可迭代对象是example_list

from itertools import ifilterfalse

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

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

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

下面是关于如何在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关于相同技术的帖子;保序字典是从他早期的一个实现扩展而来的。参见更多关于总排序的信息。

def setlist(lst=[]):
   return list(set(lst))

如果你想从列表中获取唯一的元素并保持它们的原始顺序,那么你可以使用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())

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

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