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

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

其他回答

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

> 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可以帮助您从列表中过滤出重复的元素。它适用于str, int或tuple元素,但如果您的列表包含dict或其他列表元素,那么您将以TypeError异常结束。

下面是一个通用的保序解决方案来处理一些(不是所有)不可哈希类型:

def unique_elements(iterable):
    seen = set()
    result = []
    for element in iterable:
        hashed = element
        if isinstance(element, dict):
            hashed = tuple(sorted(element.iteritems()))
        elif isinstance(element, list):
            hashed = tuple(element)
        if hashed not in seen:
            result.append(element)
            seen.add(hashed)
    return result

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

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

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

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

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