简体   繁体   English

检查子列表是否在大列表中的最快方法

[英]The fastest way to check if the sub-list exists on the large list

Suppose I have a list list1 of about 1 000 000 sub-lists. 假设我有一个大约1000000个子列表的列表list1 Next, I would like to check if the given element a , which is a sub-list, exists in the list. 接下来,我想检查给定元素a (它是一个子列表)是否存在于列表中。 Normally, it would be enough to check using if a in list1 , but with a large list it works quite slowly. 通常,只要使用if a in list1检查就足够了,但是对于较大的列表,它的运行速度非常慢。 Is there another way? 还有另一种方法吗?

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. 由于您声明可以使用元组,因此建议您将每个子列表都做成元组,然后再制作一set这些元组。 Then, searching the set will be an O(1) lookup. 然后,搜索set将是O(1)查找。 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

I want to acknowledge that @BrettBeatty originally gave this answer as well but has deleted it subsequently. 我想承认@BrettBeatty最初也给出了此答案,但随后将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM