且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-01-30 19:50:02

由于您声明可以使用元组,因此我建议将每个子列表都分成元组,然后对这些元组进行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.