从任意项列表中删除所有多个事件项的最快方法是什么(在我的示例中是列表列表)?在结果中,只显示列表中一次出现的项目,从而删除所有重复项。
输入:[[1,2],[1,3],[1,4],[1,2],[1,4],[1,2]]
输出:[[1,3],]
这个解决方案很慢:
output = [item for item in input if input.count(item)==1]
此解决方案更快:
duplicates = []
output = []
for item in input:
if not item in duplicates:
if item in output:
output.remove(item)
duplicates.append(item)
else:
output.append(item)
有没有更好的解决方案,可能首先对列表进行排序?任何想法都表示赞赏。
答案 0 :(得分:8)
如果您不关心保留订购:
from collections import Counter
def only_uniques(seq):
return [k for k,n in Counter(seq).iteritems() if n == 1]
如果你关心保留订购:
from collections import Counter
def only_uniques_ordered(seq):
counts = Counter(seq)
return [k for k in seq if counts[k] == 1]
两种算法都在O(n)
时间运行。
修改:忘了你有一份清单清单。为了能够散列序列,它需要是不可变的,所以你可以这样做:
list_of_tuples = [tuple(k) for k in list_of_lists]
然后通过上述某个功能运行list_of_tuples
。请注意,您将从中获取一个元组列表 - 但除非您在此之后专门再次修改序列,否则元组应该可以用于您的目的。
如果你做需要转换回来,它几乎是一样的:
list_of_lists = [list(k) for k in list_of_tuples]
答案 1 :(得分:2)
a = [[1, 2], [1, 3], [1, 4], [1, 2], [1, 4], [1, 2]]
print list(set(tuple(i) for i in a))
在一个班轮上方完成工作。
用户$ time python foo.py
[(1,2),(1,3),(1,4)]
真实0m0.037s
用户0m0.024s
sys 0m0.010s
仅打印发件人询问的唯一项目。解决方案是Amber解决方案的变体,除了我没有使用集合模块。
a = [[1, 2], [3, 4], [1, 3], [1, 4], [1, 2], [1, 4], [1, 2]]
d = {tuple(i): a.count(i) for i in a}
print [k for k, v in d.iteritems() if v == 1]
<强>输出:强>
[(1, 3), (3, 4)]