List:
list 的创建是以[]格式的,元素之间用","分开。其中第一个元素相印的编号为0.用len()方法可以得到list 元素的个数。创建列表如下:
cast = ["beijing","shanghai","newyork"]
调用其中某一个元素
print cast[2]
其中的“增删改”方法有:
在末尾增加一个数据项:
append 例如:
cast.append("guangzhou")
在末尾删除一个数据项 ,可使用的方法为pop(),也可以指定删除某一个元素。
在末尾增加一个数据项集合,可用的函数为extend().
在列表中找到并删去一个数据项使用的方法为remove.在特定位置前增加一个数据项用的函数为insert(0,"wuhan"
>>> cast.append("guangzhou")>>> print cast['beijing', 'shanghai', 'newyork', 'guangzhou']>>> cast.pop()'guangzhou'>>> cast.pop(-1)'newyork'>>> cast.extend(["guangzhou","newyork","wuhan"])>>> print cast['beijing', 'shanghai', 'guangzhou', 'newyork', 'wuhan']>>> cast.insert(0,"zhengzhou")>>> print cast['zhengzhou', 'beijing', 'shanghai', 'guangzhou', 'newyork', 'wuhan']>>> cast.remove("zhengzhou")>>> print cast['beijing', 'shanghai', 'guangzhou', 'newyork', 'wuhan']
处理list:
循环的格式 为 for each_item in cast for...in ...是循环的格式。
list 可以储存不同格式的数据,字符串,数字等都可以,十分灵活。
list 也可以嵌套 [...[...[...]]]
嵌套后用for循环 打印出来的 是最外围的数据项。
如果打印所有的数据项,则需要用 isinstance函数。
实例代码:
movies = ["The holy grail",1975,"terry gilliam ",91,["graham chapman ",["Michael palin" "john cleese "]]]>>> for each_movie in movies: if isinstance (each_movie,list): for each_item in each_movie: if isinstance (each_item,list): for each_bdy in each_item: print each_bdy else: print each_item else: print each_movie The holy grail1975terry gilliam91graham chapmanMichael palinjohn cleese