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

['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的构造函数。传递带有重复元素的list,我们得到带有唯一元素的set然后将它转换回带有唯一元素的list。我对性能和内存开销没有什么可说的,但我希望,对于小列表来说,这不是那么重要。

list(set(my_not_unique_list))

简单而简短。

其他回答

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

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

output = set()  # initialize an empty set

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

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

要从列表中获得唯一的值,请使用下面的代码:

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

重要的是: 如果列表中的任何项都不是可哈希的,上述方法将不起作用,这是可变类型的情况,例如list或dict。

trends = [{'super':u'nowplaying'}, u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
output = set(trends)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: unhashable type: 'dict'

这意味着你必须确保趋势列表总是只包含可哈希项,否则你必须使用更复杂的代码:

from copy import deepcopy

try:
    trends = [{'super':u'nowplaying'}, [u'PBS',], [u'PBS',], u'nowplaying', u'job', u'debate', u'thenandnow', {'super':u'nowplaying'}]
    output = set(trends)
    output = list(output)
except TypeError:
    trends_copy = deepcopy(trends)
    while trends_copy:
        trend = trends_copy.pop()
        if trends_copy.count(trend) == 0:
            output.append(trend)
print output

集合——唯一元素的无序集合。元素列表可以传递给set的构造函数。传递带有重复元素的list,我们得到带有唯一元素的set然后将它转换回带有唯一元素的list。我对性能和内存开销没有什么可说的,但我希望,对于小列表来说,这不是那么重要。

list(set(my_not_unique_list))

简单而简短。

使用以下函数:

def uniquefy_list(input_list):
"""
This function  takes a list as input and return a list containing only unique elements from the input list

"""
output_list=[]
for elm123 in input_list:
    in_both_lists=0
    for elm234 in output_list:
        if elm123 == elm234:
            in_both_lists=1
            break
    if in_both_lists == 0:
        output_list.append(elm123)

return output_list

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