检查子列表在大列表中是否存在的最快方法 [英] The fastest way to check if the sub-list exists on the large list
问题描述
假设我有一个大约1000000个子列表的列表list1
.接下来,我要检查列表中是否存在给定元素a
(它是一个子列表).通常,使用if a in list1
进行检查就足够了,但是如果列表很大,它的运行速度将非常慢.还有另一种方法吗?
Suppose I have a list list1
of about 1 000 000 sub-lists. Next, I would like to check if the given element a
, which is a sub-list, exists in the list. Normally, it would be enough to check using if a in list1
, but with a large list it works quite slowly. Is there another way?
推荐答案
由于您声明可以使用元组,因此我建议将每个子列表都分成元组,然后对这些元组进行set
制作.然后,搜索set
将是O(1)查找.虽然该集合的初始构造可能会很昂贵,但是如果您进行多次查找,那是值得的.
Since you state you can use tuples, I would recommend making each of your sub-lists into tuples and then making a set
of these tuples. Then, searching the set
will be an O(1) lookup. Initial construction of the set may be costly, though, but if you do many lookups it is worth it.
>>> set_of_sublists = {tuple(sublist) for sublist in orignal_list}
>>> tuple(sublist_to_check_for_membership) in set_of_sublists
我想承认@BrettBeatty最初也给出了此答案,但随后将其删除.
I want to acknowledge that @BrettBeatty originally gave this answer as well but has deleted it subsequently.
这篇关于检查子列表在大列表中是否存在的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!