我想从下面的列表中获得唯一的值:
['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 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'])
要从列表中获得唯一的值,请使用下面的代码:
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