我想从以下列表中获取唯一值:
['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
Run Code Online (Sandbox Code Playgroud)
我需要的输出是:
['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']
Run Code Online (Sandbox Code Playgroud)
此代码有效:
output = []
for x in trends:
if x not in output:
output.append(x)
print(output)
Run Code Online (Sandbox Code Playgroud)
我应该使用更好的解决方案吗?
最近我注意到,当我转换list到set元素的顺序发生变化,由字符排序.
考虑这个例子:
x=[1,2,20,6,210]
print x
# [1, 2, 20, 6, 210] # the order is same as initial order
set(x)
# set([1, 2, 20, 210, 6]) # in the set(x) output order is sorted
Run Code Online (Sandbox Code Playgroud)
我的问题是 -
由于dictPython 3.6 中的实现发生了变化,现在默认排序.现在还set保留秩序吗?
我找不到任何关于它的信息,但由于这两种数据结构在它们工作的方式非常相似,我认为可能就是这种情况.
我知道dict在所有情况下都无法订购s,但它们大多数情况下都是如此.如Python文档中所述:
这个新实现的顺序保留方面被认为是一个实现细节,不应该依赖它