【发布时间】:2019-08-06 03:55:52
【问题描述】:
我需要遍历一个嵌套列表,使用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 中完成任务?
【问题讨论】:
-
期望的结果是什么?
-
另外,
a = [e]似乎被滥用了。您正在制作一个包含 e 的列表,因为它是唯一的元素。get_last写得更好:lambda x: x[-1] -
最初创建一个输入列表确保我们在第一手处理一个列表。在函数的开头可以通过其他方式处理。我会将 -1 更改为 get last lambda 函数,这是一种更好的方式。但我会将代码留在原帖中,供答案和cmets参考。
-
您可以像使用递归一样模拟堆栈运算符。
l = get_last(c)喜欢推栈,但弹出栈没有出现在你的代码中,你可以尝试从这里做一些工作。 -
请问为什么不能使用递归?
标签: python recursion iteration