我想从下面的列表中获得唯一的值:
['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 getUnique(self):
notunique = self.readLines()
unique = []
for line in notunique: # Loop over content
append = True # Will be set to false if line matches existing line
for existing in unique:
if line == existing: # Line exists ? do not append and go to the next line
append = False
break # Already know file is unique, break loop
if append: unique.append(line) # Line not found? add to list
return unique
编辑:
使用字典键来检查是否存在可能会更有效,而不是对每行进行整个文件循环,我不会对大集使用我的解决方案。
你可以使用集合。为了明确起见,我正在解释列表和集合之间的区别。
集合是唯一元素的无序集合。列表是元素的有序集合。
所以,
unicode_list=[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job',u'debate', u'thenandnow']
list_unique=list(set(unicode_list))
print list_unique
[u'nowplaying', u'job', u'debate', u'PBS', u'thenandnow']
但是:不要使用list/set来命名变量。它会导致错误:
在上面的例子中,不是用list代替unicode_list。
list=[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job',u'debate', u'thenandnow']
list_unique=list(set(list))
print list_unique
list_unique=list(set(list))
TypeError: 'list' object is not callable