且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python嵌套列表递归搜索

更新时间:2023-11-28 23:17:04

您可以像这样压缩整个代码

You can squeeze your entire code like this

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

逻辑是这样的,

  1. 如果current_item等于我们要查找的数字,请返回True.

  1. If the current_item is equal to the number we are looking for, return True.

如果current_item不是list的实例,则在这种情况下为数字.如果它是一个数字并且不等于number,我们应该返回False.

If the current_item is not an instance of list, then it is a number in this case. If it is a number and it does not equal to number we should return False.

如果current_item是列表,则遍历它的每个元素,并检查是否有任何元素具有number. any在获得第一个True值后立即返回.

If the current_item is a list, then go through each and every element of it and check if any of the elements has number. any returns immediately after getting the first True value.