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 grail 1975 terry gilliam 91 graham chapman Michael palinjohn cleese