我想从下面的列表中获得唯一的值:
['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)
有更好的解决方案吗?
Python列表:
>>> a = ['a', 'b', 'c', 'd', 'b']
要获得唯一的项,只需将其转换为一个集合(如果需要,您可以将其转换回列表):
>>> b = set(a)
>>> print(b)
{'b', 'c', 'd', 'a'}
我很惊讶,到目前为止还没有人给出一个直接的维持秩序的答案:
def unique(sequence):
"""Generate unique items from sequence in the order of first occurrence."""
seen = set()
for value in sequence:
if value in seen:
continue
seen.add(value)
yield value
它将生成值,因此它不仅仅适用于列表,例如unique(range(10))。要获得一个列表,只需调用list(unique(sequence)),如下所示:
>>> list(unique([u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']))
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']
它要求每一项都是可哈希的,而不仅仅是可比较的,但Python中的大多数东西都是可哈希的,它是O(n)而不是O(n²),所以对于长列表来说很好。
通过使用Python Dictionary的基本属性:
inp=[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
d={i for i in inp}
print d
输出将是:
set([u'nowplaying', u'job', u'debate', u'PBS', u'thenandnow'])
首先,你给出的例子不是一个有效的列表。
example_list = [u'nowplaying',u'PBS', u'PBS', u'nowplaying', u'job', u'debate',u'thenandnow']
假设以上是示例列表。然后,您可以使用下面的配方来给出itertools示例文档,该文档可以返回唯一的值,并按照您的要求保留顺序。这里的可迭代对象是example_list
from itertools import ifilterfalse
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
相同顺序唯一的列表只使用一个列表压缩。
> 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
我应该指出,就性能而言,这不是一种好方法。这只是一种仅使用列表压缩来实现它的方法。