简体   繁体   English

递归遍历python中的列表

[英]Recursively traverse a list in python

In a learning exercise we were asked to traverse a multi-dimensional list and print all of its values in a single function/for loop. 在学习练习中,我们被要求遍历多维列表并在单个函数/ for循环中打印其所有值。

My brain got stuck on the basics of how a recursive function should work, through some online examples I came up with what I tought was the answer, but it stops at the first list with values it finds. 我的大脑一直停留在递归函数应该如何工作的基础上,通过一些在线示例我想出了我应该得到的答案,但它在第一个列表中停止了它找到的值。

What was the mistake of my train of tought here? 我的列车在这里犯了什么错误?

def walk(l):
    for v in l:
        if type(v) is list:
            return walk(v)
        else:
            print(v)

l = [

    [1,2,3],
    [4,5,6],
    [7,8,9]
]

walk(l)

>>1
>>2
>>3

Remove the return statement, as it stops you from going into the next iteration in the for loop (when you call walk(l) , it checks the first sub list and finds that it is a list and then encounter return, this stops the execution of the current function and so it will not go to the next iteration any more but will only execute walk([1,2,3]) and print out the results): 删除return语句,因为它阻止你进入for循环的下一次迭代(当你调用walk(l)时 ,它会检查第一个子列表并发现它是一个列表然后遇到return,这会停止执行当前函数,所以它不会再进入下一个迭代,但只会执行walk([1,2,3])并打印出结果):

def walk(l):
    for v in l:
        if type(v) is list:
            walk(v)
        else:
            print(v)

walk(l)
1
2
3
4
5
6
7
8
9

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

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