[Head First Python]1. 初始python-人人都爱列表
1 movies = [ "hello", "world",["xin","lover",["Jerry","cat"]]]
2
3 print movies
4 print "\n"
5
6 for each_1 in movies:
7 if isinstance(each_1,list):
8 for each_2 in each_1:
9 if isinstance(each_2,list):
10 for each_3 in each_2:
11 print(each_3)
12 else:
13 print(each_2)
14 else:
15 print(each_1)
16
17 def print_lol(the_list):
18 for each_item in the_list:
19 if isinstance(each_item,list):
20 print_lol(each_item)
21 else:
22 print(each_item)
23
24 print "\n"
25 print_lol(movies)
python列表看起来可能像数组, 不过还不只如此, 列表是完备的python集合对象,列表通过列表方法的形式提供一些现成得功能.
1 >>> cast = ["hello","world","!!!"] #创建列表
2 >>> print(cast); #打印列表 print
3 ['hello', 'world', '!!!']
4 >>> print(cast[1]); #列表类似数组访问
5 world
6 >>> print(len(cast)); #列表元素个数 len
7 3
8 >>> cast.append("testadd"); #列表尾添加元素 append
9 >>> print(cast)
10 ['hello', 'world', '!!!', 'testadd']
11 >>> cast.pop() #删除列表尾元素 pop
12 'testadd'
13 >>> print(cast)
14 ['hello', 'world', '!!!']
15 >>> cast.extend(["ni","hao"]) #添加列表 extend
16 >>> print(cast)
17 ['hello', 'world', '!!!', 'ni', 'hao']
18 >>> cast.remove("!!!") #删除指定元素 remove
19 >>> print(cast)
20 ['hello', 'world', 'ni', 'hao']
21 >>> cast.insert(0,"test") #插入指定元素 insert
22 >>> print(cast)
23 ['test', 'hello', 'world', 'ni', 'hao']