下面是一个简单的功能,可以在保留顺序的同时删除列表中的重复项.我已经尝试过了,它确实有效,所以这里的问题是我的理解.在我看来,第二次运行uniq.remove(item)给定项目时,它将返回错误(KeyError或者ValueError我认为?),因为该项目已从唯一集合中删除.这不是这种情况吗?
def unique(seq):
uniq = set(seq)
return [item for item in seq if item in uniq and not uniq.remove(item)]
Run Code Online (Sandbox Code Playgroud)