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

前端 未结 5 982
刺人心
刺人心 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:19

    Use a generator expression, here the whole list will not be traversed as generator generate results one by one:

    >>> lis = [['a','b','c'],['d','e','f']]
    >>> 'd' in (y for x in lis for y in x)
    True
    >>> gen = (y for x in lis for y in x)
    >>> 'd' in gen
    True
    >>> list(gen)
    ['e', 'f']
    
    ~$ python -m timeit -s "lis=[['a','b','c'],['d','e','f'],[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18]]" "'d' in (y for x in lis for y in x)"
        100000 loops, best of 3: 2.96 usec per loop
    
    ~$ python -m timeit -s "lis=[['a','b','c'],['d','e','f'],[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18]]" "'d' in [y for x in lis for y in x]"
        100000 loops, best of 3: 7.4 usec per loop
    

提交回复
热议问题