Check if an item is in a nested list

后端 未结 8 1678
死守一世寂寞
死守一世寂寞 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条回答
  •  忘掉有多难
    2020-11-28 13:31

    Try this, using the built-in any function. It's the most idiomatic solution, and it's also efficient, because any short-circuits and stops as soon as it finds the first match:

    x = [[1, 2, 3], [2, 3, 4]]
    any(2 in sl for sl in x)
    => True
    

提交回复
热议问题