Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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,我用python编程已经4周了,现在我们讨论的是递归 问题陈述 我需要写一个带有一个参数的函数,这个参数是一个列表;函数必须检查列表及其子列表是否满足以下条件: 列表中的所有元素都是整数 或 列表中的所有元素都是列表 和所有子列表也满足标准 例如: [1, 2] True [[1, 2, [1]]] False [[1], [2], [[3], [1]]] True 等等 我迄今为止的努力 我试着先检查宽度,然后再检查深度。一层一层往深

我用python编程已经4周了,现在我们讨论的是递归

问题陈述 我需要写一个带有一个参数的函数,这个参数是一个列表;函数必须检查列表及其子列表是否满足以下条件:

  • 列表中的所有元素都是整数

  • 列表中的所有元素都是列表
  • 所有子列表也满足标准
例如:

[1, 2]                 True
[[1, 2, [1]]]          False
[[1], [2], [[3], [1]]] True
等等

我迄今为止的努力 我试着先检查宽度,然后再检查深度。一层一层往深处走。 但这是行不通的,因为在某一点上

[[1], [2], [[3], [1]]]

1, 2, [3], [1] 
这是错误的

我意识到我需要先进入深度,如果我不能进入深度,我会检查所有需要回去的东西。有点像二叉树。这就是我的问题。我不知道我什么时候才能回到我的“剩菜”清单上来

def intSuperListe(列表到检查):
对于idx,枚举中的项(列表到检查):
如果idx+1
这是我的尝试


非常感谢您的帮助。

您可以编写反映需求的代码:

如果列表中的所有项目都是
int
s,则返回
True

如果列表中的所有项目都是
list
s且这些子列表也符合要求,则返回
True

否则返回
False

def intSuperListe(列表到检查):
areInts=all(列表中项目的isinstance(项目,int)到检查)
如有必要:
返回真值
areLists=all(列表中项目的isinstance(项目,列表)\u至\u检查)
如有下列情况:
返回所有(列表中项目的intSuperListe(项目)_to_check)
返回错误
[1,2]、[1,2[1]]、[1]、[2]、[3]、[1]]中的项目:
打印(IntSuperList(项目),项目)
输出:

True[1,2]
假[[1,2,1]]
真[[1]、[2]、[3]、[1]]
def INTSUPERLIST(列表到检查):
如果全部(映射(lambda x:isinstance(x,int),列出检查):
返回真值
elif all(映射(λx:isinstance(x,列表),列表到检查)):
返回全部(映射(IntSuperList,列表到检查))
返回错误
>a=[1,2]
>>>b=[[1,2,1]]
>>>c=[[1]、[2]、[3]、[1]]
>>>打印(intSuperListe(a))
真的
>>>打印(intSuperListe(b))
假的
>>>打印(intSuperListe(c))
真的

请用您尝试过的代码更新您的问题。您需要先进行广度分析,而不是深度分析。在检查任何列表之前,您需要查看所有元素是否都是列表或整数。
def intSuperListe(lst):

    if all([type(l) == int for l in lst]):
        # if all elements of lst are ints then this is True
        return True
    elif all([type(l) == list for l in lst]):
        # if all elements of lst are lists, recursively check
        # all elements by calling intSuperListe on each
        return all([intSuperListe(l) for l in lst])
    else:
        # If all elements are not list or ints, then return
        # False
        return False


a = [1, 2]
b = [[1, 2, [1]]]
c = [[1], [2], [[3], [1]]]

print(intSuperListe(a))
print(intSuperListe(b))
print(intSuperListe(c))

>>> True
>>> False
>>> True