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

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

    Using list comprehension, given:

    mylist = [['a','b','c'],['d','e','f']]
    'd' in [j for i in mylist for j in i]
    

    yields:

    True
    

    and this could also be done with a generator (as shown by @AshwiniChaudhary)

    Update based on comment below:

    Here is the same list comprehension, but using more descriptive variable names:

    'd' in [elem for sublist in mylist for elem in sublist]
    

    The looping constructs in the list comprehension part is equivalent to

    for sublist in mylist:
       for elem in sublist
    

    and generates a list that where 'd' can be tested against with the in operator.

提交回复
热议问题