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

['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 = list(set(mylist))

其他回答

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

从List中获取唯一元素

mylist = [1,2,3,4,5,6,6,7,7,8,8,9,9,10]

从集合中使用简单的逻辑-集合是唯一的项目列表

mylist=list(set(mylist))

In [0]: mylist
Out[0]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

使用简单逻辑

newList=[]
for i in mylist:
    if i not in newList:
        newList.append(i)

In [0]: mylist
Out[0]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

使用pop方法 ->pop删除最后一个或索引项,并显示给用户。视频

k=0
while k < len(mylist):
    if mylist[k] in mylist[k+1:]:
        mylist.pop(mylist[k])
    else:
        k=k+1

In [0]: mylist
Out[0]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

使用Numpy

import numpy as np
np.unique(mylist)

In [0]: mylist
Out[0]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

参考

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

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]
def get_distinct(original_list):
    distinct_list = []
    for each in original_list:
        if each not in distinct_list:
            distinct_list.append(each)
    return distinct_list

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

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

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