Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python嵌套列表递归搜索_Python_List_Recursion - Fatal编程技术网

Python嵌套列表递归搜索

Python嵌套列表递归搜索,python,list,recursion,Python,List,Recursion,给定一个嵌套列表L(这样L的每个元素要么是一个整数,要么是一个列表,它本身可能是 包含整数或列表,这些整数或列表可能依次…等)返回真实的i,s在L中 search([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8) 应该返回True 以下是我到目前为止的情况: def search (L,s): """(list, anytype) _> Bool Returns true iff s is present in L """ if L:

给定一个嵌套列表L(这样L的每个元素要么是一个整数,要么是一个列表,它本身可能是 包含整数或列表,这些整数或列表可能依次…等)返回真实的i,s在L中

search([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8) 
应该返回True

以下是我到目前为止的情况:

def search (L,s):
"""(list, anytype) _> Bool
Returns true iff s is present in L
"""
if L:
    if L[0] == s:
        return True
    else:
        return search (L[1:], s)
else:
    return False
如果列表不是嵌套的,或者是嵌套的(嵌套的元素是最后一个元素),则当前代码适用于列表:

但不适用于以下情况:

[1, 2, [3, 4], 5]
如何更改代码以使其适用于嵌套列表?嵌套元素位于列表中的任何位置,而不是严格意义上的最后一个元素

谢谢你的帮助


编辑:抱歉,忘记指定它需要是递归的。

您可以这样压缩整个代码

def search(current_item, number):
    if current_item == number: return True
    return isinstance(current_item, list) \
        and any(search(item, number) for item in current_item)
for i in range(12):
    print i, search([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], i)
你可以这样测试它

def search(current_item, number):
    if current_item == number: return True
    return isinstance(current_item, list) \
        and any(search(item, number) for item in current_item)
for i in range(12):
    print i, search([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], i)
输出

0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True
10 True
11 False
逻辑是这样的,

  • 如果
    当前\u项
    等于我们要查找的数字,则返回
    True

  • 如果
    当前\u项
    不是列表的实例,则在本例中它是一个数字。如果它是一个数字并且不等于
    number
    ,我们应该返回
    False

  • 如果
    当前\u项是一个列表,则检查其中的每个元素,并检查是否有任何元素具有
    编号
    any
    在获得第一个
    True
    值后立即返回


  • 如果项目在列表中的什么位置无关紧要,那么类似的事情应该可以解决

    def unpack(iterable):
       result = []
       for x in iterable:
          if hasattr(x, '__iter__'):
             result.extend(unpack(x))
          else:
             result.append(x)
       return result
    
     >>> unpack([1,2,3,[4,5,6],7,[8,[9,10],11,]])
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    

    抱歉,我忘了指定我需要使用递归。这确实使用递归-请参阅最后一行对
    search
    的递归调用。您能解释一下代码的最后两行吗?我理解
    isinstance
    any
    ,但我不确定它们放在一起时会做什么that@NickGong现在请核对我的答案。我已经添加了基本的解释。这是一个很好的算法,可以放在你常用的工具中。很遗憾,
    itertools flatte
    配方中没有这样的东西。作为生成器,您的算法可能会更好,因为它解包的列表可能非常大。非常有趣,它对我来说非常好,我会记住这一点以备将来参考。但在这个练习中,我需要像那样设置参数并使用递归。谢谢你!你能解释一下你的答案吗?