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.
Remember that Python limits 1000 stack frames stacked. So, if your list have more than 1000 items, you should get an Exception.
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