python跳出深度循环,Python:如何循环变化深度的列表?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值