繁体   English   中英

在嵌套列表中查找索引

[英]Finding index in nested list

我正在尝试创建一个 function ,它将一个嵌套列表和一个项目作为输入,并返回一个索引列表。 例如list = [0, 5, [6, 8, [7, 3, 6]], 9, 10]item = 7应该返回[2, 2, 0] ,因为list[2][2][0] = 7

我的代码应该可以工作,因为我可以打印需求 output,但是当我运行它时它返回 None。

def find_item(list_input, item, current):
    if list_input == item:
        print(current) ## this does give the desires output, but the function should return not print
        return current
    else:
        if isinstance(list_input, list):
            for j in range(len(list_input)):
                current.append(j)
                find_item(list_input[j], item, current)
                del current[-1]

我在这里俯瞰什么?

正如@tzaman 提到的,您需要处理find_item递归调用的返回值。 如果递归调用的返回值是一个列表,则表示找到了搜索项,我们需要停止递归。

以下修改将返回搜索项的最早找到的索引。 如果没有找到项目,它将返回None

def find_item(list_input, item, current):
    if list_input == item:
        return current
    else:
        if isinstance(list_input, list):
            for j in range(len(list_input)):
                current.append(j)
                search_result = find_item(list_input[j], item, current)
                if isinstance(search_result, list):
                    return search_result
                del current[-1]

list_input  = [0, 5, [6, 8, [7, 3, 6]], 9, 10]
item = 7
print(find_item(list_input, item, []))

list_input  = [0, 5, [6, 8, [7, 3, 6]], 9, 10]
item = 9
print(find_item(list_input, item, []))

list_input  = [0, 5, [6, 8, [7, 3, 6]], [30, 4], 9, 10]
item = 4
print(find_item(list_input, item, []))

list_input  = [0, 5, [6, 8, [7, 3, 6]], [30, 4], 9, 10]
item = 400
print(find_item(list_input, item, []))

Output:

[2, 2, 0]
[3]
[3, 1]
None

当有人在递归function 中间插入一个for循环时,它总是困扰我:这是 go 关于这个问题的不同方法:

def find_item(list_input, item, index=0):
    if list_input:
        head, *tail = list_input

        if head == item:
            return [index]

        if isinstance(head, list):
            if result := find_item(head, item):
                return [index] + result

        return find_item(tail, item, index + 1)
    
    return list_input

list_input  = [0, 5, [6, 8, [7, 3, 1]], 9, 10]

print(find_item(list_input, 7))

此解决方案不需要明确的第三个参数。 并在找不到项目时返回一个空list ,而不是None 注意新海象运算符的使用:=

            if result := find_item(head, item):

如果这是一个问题,请改为:

            result = find_item(head, item)
            if result:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM