我需要遍历嵌套列表,使用 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]
有关其工作原理的一些说明:
- 如果列表
a
中的pop
生成一个整数,我们只需将字符串化的整数附加到res
- 如果我们的列表
a
上的pop
产生一个内部列表,我们需要开始处理该内部列表,然后再处理出现在该内部列表之后的元素。处理完内部列表后,我们将不得不回到a
的剩余未弹出元素。 - 每当我们检测到当前列表
a
已变为空时,我们的res
将指向等效的字符串化列表,现在是我们附加的时候了code>res
到它的(字符串化的)外部列表 - 为了处理每个遇到的内部列表,我们采用该内部列表作为我们的新
a
(赋值a = elem
),并将一个空列表作为我们的新res
(res = []
)。在此之前,我们需要将当前的a
和当前的res
压入堆栈
- 为什么采用后进先出法?好吧,这样看:无论什么被压入 last 到
my_stack
都代表我们当前正在处理的任何列表的直接外部列表(a
).
关于python - 嵌套列表的非递归遍历——在Python中构建一个类似的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55176342/