python - 嵌套列表的非递归遍历——在Python中构建一个类似的嵌套列表

标签 python recursion iteration

我需要遍历嵌套列表,使用 str() 处理每个非列表项并返回保持结构的类似列表。使用递归会很容易,但我需要以这种迭代方式进行。下面是我对 while 循环的尝试:

def myiter(e):
    a = [e] # initial list
    c = [[]] # final result
    get_last = lambda x: x[len(x)-1] # get ref to the final sublist
    l = get_last(c)
    while a:
        b = a.pop(0)
        if isinstance(b, list):
            # if there are more items to process in the original list
            if a:
                a = b + a
            # else extend original list to process sublists
            else:
                a.extend(b)
            # make a new sublist ref
            l = get_last(c)
            c.append([])
        else:
             # walk and process every item in the nested list
             l.append(str(b))
    return c

这有几个问题,输出将显示:

myiter([1, [2, [3, 4], 5]]) # [['1'], ['2'], ['3', '4', '5'], []]

期望的结果是:

['1', ['2', ['3', '4'], '5']]

在 Python 中是否有一种简单的迭代方法来完成任务?

最佳答案

这似乎可行:

def stringify(a):
    a = a[:]                           # Make copy of what was passed in.
    res = []                           # Initialize result list.
    my_stack = []                      # Initialize our own LIFO stack.
    while (a or my_stack):                            # While a or my_stack is non-empty
        if (a):
            elem = a.pop(0)
            if (not isinstance(elem, list)):          # If popped elem is not a list
                res.append(str(elem))                 # Append stringified elem to res
            else:
                my_stack.append((a, res))           # Push some stuff, to resume working upon later.
                a = elem                            # Let's start iterating on this inner list
                res = []                            # This inner list needs a clean res, to start with.
        else:                                       # my_stack is non-empty
            a, res_prev = my_stack.pop()   # Pop some stuff, to resume, work on outer list
            res_prev.append(res)           # First, append our just-completed inner list.
            res = res_prev
    return res

输出:

a = [1, [2, [3, 4], 5]]
stringify(a)
['1', ['2', ['3', '4'], '5']]

通过了以下测试用例:

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

有关其工作原理的一些说明:

  1. 如果列表a 中的pop 生成一个整数,我们只需将字符串化的整数附加到res
  2. 如果我们的列表a 上的pop 产生一个内部列表,我们需要开始处理该内部列表,然后再处理出现在该内部列表之后的元素。处理完内部列表后,我们将不得不回到 a 的剩余未弹出元素。
  3. 每当我们检测到当前列表 a 已变为空时,我们的 res 将指向等效的字符串化列表,现在是我们附加 的时候了code>res 到它的(字符串化的)外部列表
  4. 为了处理每个遇到的内部列表,我们采用该内部列表作为我们的新a(赋值a = elem),并将一个空列表作为我们的新res (res = [])。在此之前,我们需要将当前的 a 和当前的 res
  5. 压入堆栈
  6. 为什么采用后进先出法?好吧,这样看:无论什么被压入 lastmy_stack 都代表我们当前正在处理的任何列表的直接外部列表(a ).

关于python - 嵌套列表的非递归遍历——在Python中构建一个类似的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55176342/

相关文章:

python - 从 CSV 文件创建图形并使用 Django 和 Pandas Python 库呈现到浏览器

c++测试以检查函数是否递归实现

java - 递归和不同的列表

python - python 迭代两个数组的快速方法

java - 如何洗牌由二维数组组成的牌组

python - 如何遍历列表,获取每对可能的值?

python - 如何将 formbuilder 制作的表单添加到 Wagtail 中的每个页面?

python - Django:Internet Explorer 下载页面内容而不是渲染它

列表列表中的 Python 函数参数

c++ - 递归逃出迷宫