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

['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 unique(a):

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



    return a

其他回答

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

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)

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

Set是一个无序且唯一元素的集合。所以,你可以使用set来获得一个唯一的列表:

unique_list = list(set([u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']))

你的输出变量是什么类型?

Python集是你所需要的。像这样声明输出:

output = set()  # initialize an empty set

你已经准备好使用output.add(elem)添加元素,并确保它们是唯一的。

警告:集合不保留列表的原始顺序。

维持秩序:

# oneliners
# slow -> . --- 14.417 seconds ---
[x for i, x in enumerate(array) if x not in array[0:i]]

# fast -> . --- 0.0378 seconds ---
[x for i, x in enumerate(array) if array.index(x) == i]

# multiple lines
# fastest -> --- 0.012 seconds ---
uniq = []
[uniq.append(x) for x in array if x not in uniq]
uniq

顺序不重要:

# fastest-est -> --- 0.0035 seconds ---
list(set(array))

在代码开始时,只需将输出列表声明为空:output=[] 您可以使用以下代码代替您的代码trends=list(set(trends))