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)