猿问

Python 搜索嵌套列表时出现意外行为

我正在尝试编写一个递归算法,在嵌套数组中搜索整数。


这就是我目前的代码,我添加了 print 语句来查看它每次迭代的作用。输出显示它应该True在某个时刻返回,即使它没有返回。


def nestedListContains(lst, n):

    for i in lst:

        print(f'i: {i}, n: {n}')

        if type(i) == list:

            nestedListContains(i, n)

        elif int(i) == int(n):

            return True

    return False



print(nestedListContains([1, [2, [3], 4]], 3)) # Should return True

print(nestedListContains([1, [2, [3], 4]], 5)) # Should return False

输出:


i: 1, n: 3

i: [2, [3], 4], n: 3

i: 2, n: 3

i: [3], n: 3

i: 3, n: 3 # This iteration should return True!

i: 4, n: 3

False


i: 1, n: 5

i: [2, [3], 4], n: 5

i: 2, n: 5

i: [3], n: 5

i: 3, n: 5

i: 4, n: 5

False


qq_遁去的一_1
浏览 121回答 2
2回答

qq_花开花谢_0

当您调用递归函数时,您缺少 a ,return因为这将是返回的函数Truedef nestedListContains(lst, n):    for i in lst:        print(f'i: {i}, n: {n}')        if type(i) == list:            return nestedListContains(i, n)        elif int(i) == int(n):            return True    return Falseprint(nestedListContains([1, [2, [3], 4]], 3))  # Trueprint(nestedListContains([1, [2, [3], 4]], 5))  # False

holdtom

您需要返回调用的值nestedListContains(i, n),否则返回的值将被丢弃,并且循环将继续,直到return False到达:def nestedListContains(lst, n):    for i in lst:        print(f'i: {i}, n: {n}')        if type(i) == list:            return nestedListContains(i, n)        elif int(i) == int(n):            return True    return False
随时随地看视频慕课网APP

相关分类

Python
我要回答