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

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

有更好的解决方案吗?


当前回答

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

def get_unique_list(lst):
        if isinstance(lst,list):
            return list(set(lst))

其他回答

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

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)

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

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

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

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

我的解决方案,检查内容的唯一性,但保留原来的顺序:

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

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

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

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]