Check if an item is in a nested list

后端 未结 8 1653
死守一世寂寞
死守一世寂寞 2020-11-28 12:32

in a simple list following check is trivial:

x = [1, 2, 3]

2 in x  -> True

but if it is a list of list, such as:

x = [[         


        
8条回答
  •  萌比男神i
    2020-11-28 13:30

    The Óscar Lopez answer is so great! I recommend to use it.

    However, you can use itertools to flatten the list and eval it, so:

    import itertools
    
    x = [[1, 2, 3], [2, 3, 4]]
    2 in itertools.chain.from_iterable(x)
    
    Output: True
    

    Also, you can make it "manually" through comprehension:

    x = [[1, 2, 3], [2, 3, 4]]
    2 in [item for sub_list in x for item in sub_list]
    
    Output: True
    

    These're only other ways to make it, good luck.

提交回复
热议问题