递归遍历列表

 1 # *-* coding: utf-8 *-*
 2 
 3 #列表是可变的,有序的. 列表中可以存放任意混合数据类型
 4 
 5 cast = ["Cleese", "Palin", "Jones", "Idle"]
 6 print(cast)
 7 
 8 #len() 获得列表长度
 9 print(len(cast))
10 #使用索引方式访问列表, 索引从 0 开始
11 print(cast[1])
12 #list.append() 在列表末尾添加一个数据项
13 cast.append("Gilliam")
14 #list.pop(index) 从列表末尾删除一个数据项, 不带参数默认最后一个数据项, 返回被删除的数据
15 print(cast.pop())
16 #list.extend() 在列表末尾增加一个数据集合
17 cast.extend(["Gilliam","Chapman"])
18 #list.remove() 删除列表中指定的数据项
19 cast.remove("Chapman")
20 #list.insert() 在指定位置增加数据项, 按索引位置
21 cast.insert(0, "Chapman")
22 #isinstance(name, list) , 检查一个对象是否是列表, 返回 True 或 False
23 print(isinstance(cast, list))
24 
25 #遍历列表
26 for temp in cast:
27     print(temp)
28 
29 count = 0
30 while count < len(cast):
31     print(cast[count])
32     count += 1
33 
34 
35 
36 
37 #嵌套列表遍历读取
38 movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91,
39           ["Graham Chapman", ["Michael Palin", "John Cleese",
40                               "Terry Gilliam", "Eric Idle", "Terry Jones"]]]
41 
42 print(movies)
43 
44 for temp1 in movies:
45 
46     if isinstance(temp1, list):
47 
48         for temp2 in temp1:
49 
50             if isinstance(temp2, list):
51 
52                 for temp3 in temp2:
53 
54                     print(temp3)
55 
56             else:
57 
58                 print(temp2)
59 
60     else:
61         print(temp1)
62 
63 #使用递归解决嵌套列表遍历读取
64 def print_lol(self, the_list):
65     for temp in the_list:
66         if isinstance(temp, list):
67             print_lol(temp)
68     else:
69         print(temp)
70 
71 print_lol(movies)

 

转载于:https://www.cnblogs.com/Roger1227/archive/2013/06/10/3130325.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值