![](/img/trans.png)
[英]The fastest way to remove items that matches a substring from list - Python
[英]Fastest way to remove all multiple occurrence items from a list?
从任意项列表中删除所有多个事件项的最快方法是什么(在我的示例中是列表列表)? 在结果中,只显示列表中一次出现的项目,从而删除所有重复项。
输入:[[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)
有没有更好的解决方案,可能首先对列表进行排序? 任何想法都表示赞赏。
如果您不关心保留订购:
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]
a = [[1, 2], [1, 3], [1, 4], [1, 2], [1, 4], [1, 2]]
print list(set(tuple(i) for i in a))
在一个衬垫上方完成工作。
user $ 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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.