Check if an item is in a nested list

后端 未结 8 1641
死守一世寂寞
死守一世寂寞 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:21

    Here's a recursive version that works for any level of nesting.

    def in_nested_list(my_list, item):
        """
        Determines if an item is in my_list, even if nested in a lower-level list.
        """
        if item in my_list:
            return True
        else:
            return any(in_nested_list(sublist, item) for sublist in my_list if isinstance(sublist, list))
    

    Here are a few tests:

    x = [1, 3, [1, 2, 3], [2, 3, 4], [3, 4, [], [2, 3, 'a']]]
    print in_nested_list(x, 2)
    print in_nested_list(x, 5)
    print in_nested_list(x, 'a')
    print in_nested_list(x, 'b')
    print in_nested_list(x, [])
    print in_nested_list(x, [1, 2])
    print in_nested_list(x, [1, 2, 3])
    
    True
    False
    True
    False
    True
    False
    True
    

提交回复
热议问题