我想从下面的列表中获得唯一的值:
['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'}
通过使用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'])
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