admin管理员组

文章数量:1320588

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” 
——. . .

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” 
——. . .
Share Improve this question edited Jan 17 at 23:12 Barmar 783k56 gold badges547 silver badges660 bronze badges asked Jan 17 at 23:07 user29249433user29249433 134 bronze badges 5
  • Please remember to turn off "smart quotes" when posting code. – Barmar Commented Jan 17 at 23:11
  • I’m typing this on a phone sorry – user29249433 Commented Jan 17 at 23:13
  • Can Hello and Hi be at any level of nesting, or do you just need to check at the levels in your example? – Barmar Commented Jan 17 at 23:13
  • I need the nesting to be exact – user29249433 Commented Jan 17 at 23:14
  • The input is nested, but do you not just need to know that mylist[0] satisfies your criteria? Alternatively, is what you need as a result more like mylist[0][0] + mylist[0][1][0]? – JonSG Commented Jan 17 at 23:20
Add a comment  | 

3 Answers 3

Reset to default 1

You can just ask whether it's in there:

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

Attempt This Online!

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))

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")

本文标签: How to check for specific structure in nested list pythonStack Overflow