Python:如何循环变化深度的列表? [英] Python: How to loop a list of lists of varying depth?
问题描述
我有一个像这样的数据结构(列表的实际列表很长且深度不同).我确实知道他们的深度.
I have a data structure like this (the actual lists of lists are very long and of varying depth). I do know their depth beforehand.
a=( [1,2], [2,3,[4,5]] )
b=( [[1,2],[2,3]] )
一个要遍历每个列表的地方.如何做到最好?
A want to loop through each single list. How to best do this?
我不想最终做这样的事情:
I don't want to end up doing something like this:
for l in a:
if instance(l, list):
for ll in l:
if instance(ll, list):
...
推荐答案
由于您未定义目的,因此我正在编写一个对所有元素求和的函数:
Since you don't defined the purpose, i'm coding a function that sum all elements:
def rec_sum(lst):
if not lst:
return 0
el = lst.pop()
if isinstance(el, list):
return rec_sum(el) + rec_sum(lst)
else:
return el + rec_sum(lst)
即使您事先知道深度,使用递归也更容易解决.
Even if you know the depth beforehand, it's easier to solve using recursion.
请记住,Python限制堆叠的1000个堆栈帧.因此,如果您的列表中包含1000多个项目,则应该获得Exception.
Remember that Python limits 1000 stack frames stacked. So, if your list have more than 1000 items, you should get an Exception.
如果您认为可以有1000多个项目,那么这里是一个混合解决方案,它使用递归和for循环.它被限制为1000个级别,而不是1000个项目:
If you think you can have more than 1000 items, here it is a mixed solution, that uses recursion and for loops. It is limited into 1000 levels, instead of 1000 items:
def rec_for_sum(lst):
if not lst:
return 0
count = 0
for el in lst:
if not isinstance(el, list):
count += el
else:
count += rec_for_sum(el)
return count
这篇关于Python:如何循环变化深度的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!