简体   繁体   中英

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. 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?

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

I want to acknowledge that @BrettBeatty originally gave this answer as well but has deleted it subsequently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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