I am trying to search a nested list using python. For example, the function is nestedListContains(NL, target). nestedListContains([1, [2, [3], 4]], 3) should return True but nestedListContains([1, [2, [3], 4]], 5) should return False.
What I tried:
def nestedListContains(NL, target):
if target not in NL:
return False
else:
return True
The examples I gave work but if it's nestedListContains([[9, 4, 5], [3, 8]], 3) then it gives me the wrong return value. How do I fix this?
解决方案
Something like this?
def nested_list_contains(nl, target):
for thing in nl:
if type(thing) is list:
if nested_list_contains(thing, target):
return True
if thing == target:
return True
return False
print(nested_list_contains([1, [2, [3], 4]], 3)) # True
print(nested_list_contains([1, [2, [3], 4]], 5)) # False