我想从下面的列表中获得唯一的值:
['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标准库中的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())
在引入字典的“紧凑”表示之后,这成为可能。点击这里查看。尽管这“被认为是一个实现细节,不应该依赖”。
通过使用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'])
除了前面的答案,你可以把你的列表转换成集合,你也可以用这种方式
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenadnow']
mylist = [i for i in set(mylist)]
输出将是
[u'nowplaying', u'job', u'debate', u'PBS', u'thenadnow']
尽管秩序将不复存在。
另一个更简单的答案是(不使用集合)
>>> t = [v for i,v in enumerate(mylist) if mylist.index(v) == i]
[u'nowplaying', u'PBS', u'job', u'debate', u'thenadnow']
我很惊讶,到目前为止还没有人给出一个直接的维持秩序的答案:
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²),所以对于长列表来说很好。