user29249433
user29249433

Reputation: 13

How to check for specific structure in nested list python

Suppose we have the list:

mylist = [
    [
        "Hello",
        [
            "Hi"
        ]
    ]
]

How do I check that list containing "Hello" and "Hi" exists in mylist, in specifically this structure without flattening it?

All the solutions are flattening the list, but I need to check for specific structure, like this

Array
|_
—-|_ “Hello”
———|_ “Hi” 
——. . .

Upvotes: 1

Views: 59

Answers (3)

no comment
no comment

Reputation: 10122

You can just ask whether it's in there:

["Hello", ["Hi"]] in mylist

Attempt This Online!

Upvotes: 1

Barmar
Barmar

Reputation: 780598

Use the any() function and the in operator.

if any("Hello" in sublist and any("Hi" in subsublist for subsublist in sublist if isinstance(subsublist, list)) for sublist in mylist):
    print("Hello and Hi were found")

Upvotes: 1

Michal
Michal

Reputation: 5690

To check if the specific nested structure exists in mylist without flattening it, you can use recursion to traverse the structure and compare it element by element.

def is_structure_present(haystack, needle):
    if not isinstance(needle, list) or not isinstance(haystack, list):
        return haystack == needle
    
    if len(needle) != len(haystack):
        return False
    
    return all(is_structure_present(h, n) for h, n in zip(haystack, needle))

# Your list
mylist = [
    [
        "Hello",
        [
            "Hi"
        ]
    ]
]

# The structure to check
structure_to_check = [
    "Hello",
    [
        "Hi"
    ]
]

# Check if the structure exists
print(any(is_structure_present(item, structure_to_check) for item in mylist))

Upvotes: 1

Related Questions