我想从下面的列表中获得唯一的值:
['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)
有更好的解决方案吗?
除了前面的答案,你可以把你的列表转换成集合,你也可以用这种方式
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']
通过使用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'])
我的解决方案,检查内容的唯一性,但保留原来的顺序:
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
编辑:
使用字典键来检查是否存在可能会更有效,而不是对每行进行整个文件循环,我不会对大集使用我的解决方案。