我想从下面的列表中获得唯一的值:
['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)
有更好的解决方案吗?
相同顺序唯一的列表只使用一个列表压缩。
> my_list = [1, 2, 1, 3, 2, 4, 3, 5, 4, 3, 2, 3, 1]
> unique_list = [
> e
> for i, e in enumerate(my_list)
> if my_list.index(e) == i
> ]
> unique_list
[1, 2, 3, 4, 5]
enumates以元组的形式给出索引I和元素e。
my_list。index返回e的第一个索引。如果第一个索引不是i,则当前迭代的e不是列表中的第一个e。
Edit
我应该指出,就性能而言,这不是一种好方法。这只是一种仅使用列表压缩来实现它的方法。
我的解决方案,检查内容的唯一性,但保留原来的顺序:
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
编辑:
使用字典键来检查是否存在可能会更有效,而不是对每行进行整个文件循环,我不会对大集使用我的解决方案。
首先正确地声明列表,用逗号分隔。您可以通过将列表转换为集合来获得唯一的值。
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)
如果你进一步将其作为列表使用,你应该通过以下操作将其转换回列表:
mynewlist = list(myset)
另一种可能,可能更快的是,从一开始就使用集合,而不是列表。那么你的代码应该是:
output = set()
for x in trends:
output.add(x)
print(output)
正如已经指出的那样,集合不保持原来的顺序。如果你需要它,你应该寻找一个有序集实现(更多信息请参阅这个问题)。