What is the most efficient way to search nested lists in python?

前端 未结 5 981
刺人心
刺人心 2020-12-01 11:24

I have a list that contains nested lists and I need to know the most efficient way to search within those nested lists.

e.g., if I have

[[\'a\',\'b\         


        
5条回答
  •  情深已故
    2020-12-01 12:10

    If your arrays are always sorted as you show, so that a[i][j] <= a[i][j+1] and a[i][-1] <= a[i+1][0] (the last element of one array is always less than or equal to the first element in the next array), then you can eliminate a lot of comparisons by doing something like:

    a = # your big array
    
    previous = None
    for subarray in a:
       # In this case, since the subarrays are sorted, we know it's not in
       # the current subarray, and must be in the previous one
       if a[0] > theValue:
          break
       # Otherwise, we keep track of the last array we looked at
       else:
          previous = subarray
    
    return (theValue in previous) if previous else False
    

    This kind of optimization is only worthwhile if you have a lot of arrays and they all have a lot of elements though.

提交回复
热议问题