Python通过递归函数输出嵌套列表元素
作者:lincappu 时间:2021-03-23 15:36:09
1.先用 for 循环取
for item in l:
if isinstance(item ,list):
for newitem in item:
print(newitem)
else:
print(item
输出:
1
2
3
4
5
6
#利用 for 循环取值,有几层嵌套就要写几层 for 循环,否则不识别。
l=[1,2,[3,4],[5,6,[7,8]]]
for item in l:
if isinstance(item ,list):
for newitem in item:
print(newitem)
else:
print(item
输出
1
2
3
4
5
6
[7, 8]
2.递归函数实现:
递归函数实现:
def getitem(l):
for item in l:
if isinstance(item,list):
getitem(item)
else:
print(item)
getitem(l)
输出:
1
2
3
4
5
6
7
8
9
10
变式1:遇到类表就缩进一次:
def getitem(l,level=0):
for item in l:
if isinstance(item,list):
getitem(item,level+1)
else:
for tab in range(level):
print('\t',end='' #输出一个 制表符,并且将 print 后面的换行符去掉,这样就是了缩进
print(item)
getitem(l)
输出
变式2:加入开启机制,是否缩进
def getitem(l,level=0,count=False):
for item in l:
if isinstance(item,list):
getitem(item,level+1,count)
else:
if count:
for tab in range(level):
print('\t',end='' #输出一个 制表符,并且将 print 后面的换行符去掉,这样就是了缩进
print(item)
print(item)
getitem(l)
输出
1
2
3
4
5
6
7
8
9
10
来源:https://www.cnblogs.com/lincappu/p/8146055.html
标签:Python,递归,函数,嵌套
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP的SQL注入过程分析
2023-11-18 02:53:27
python定时任务timeloop库用法实例详解
2023-12-21 19:34:53
![](https://img.aspxhome.com/file/2023/9/99689_0s.png)
pytorch中使用LSTM详解
2021-01-08 04:27:10
![](https://img.aspxhome.com/file/2023/4/89394_0s.jpg)
网页中插入视频播放代码全集
2007-10-22 17:48:00
Python浪漫玫瑰盛开表白源代码
2022-03-18 11:27:00
![](https://img.aspxhome.com/file/2023/1/130751_0s.png)
动态程序防采集的新方法
2010-04-24 15:24:00
Python通过dxfgrabber库实现获取CAD信息
2021-02-26 00:18:49
![](https://img.aspxhome.com/file/2023/0/127750_0s.png)
Python数据类型之列表和元组的方法实例详解
2021-01-18 01:56:10
![](https://img.aspxhome.com/file/2023/4/107814_0s.jpg)
Django项目连接MongoDB的三种方法
2022-05-27 05:23:43
asp检测文件编码方法
2007-10-03 14:27:00
Mootools常用方法扩展(三)
2009-01-14 20:07:00
SQL Server 数据页缓冲区的内存瓶颈分析
2012-08-21 10:49:11
彻底删除thinkphp3.1案例blog标签的方法
2023-11-21 12:01:01
使用pycharm生成代码模板的实例
2021-03-07 04:57:52
数据库性能优化之冗余字段的作用
2011-03-03 19:21:00
MySql常用命令总结
2009-09-16 10:51:00
python实现通讯录管理系统
2022-01-31 08:25:31
详解Python解决抓取内容乱码问题(decode和encode解码)
2021-12-18 09:26:29
![](https://img.aspxhome.com/file/2023/0/115720_0s.png)
Python实现并行抓取整站40万条房价数据(可更换抓取城市)
2021-09-24 10:56:43
![](https://img.aspxhome.com/file/2023/7/76067_0s.png)
python 连续不等式语法糖实例
2021-11-03 02:15:20