本文介绍了Python:如何使用递归搜索嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python搜索嵌套列表.例如,函数为nestedListContains(NL, target). nestedListContains([1, [2, [3], 4]], 3)应该返回True,但是nestedListContains([1, [2, [3], 4]], 5)应该返回False.

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.

我尝试过的事情:

def nestedListContains(NL, target):
   if target not in NL:
      return False
   else:
      return True

我给出的示例工作,但是如果它是nestedListContains([[9,4,5],[3,8]],3),那么它给我错误的返回值.我该如何解决?

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?

推荐答案

像这样吗?

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

这篇关于Python:如何使用递归搜索嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 07:06