#coding=utf-8#列表方法(append,count,extend,index,insert,pop,remove,reverse,sort)'''調用格式:對象.方法(參數)'''#appendlst=['a','b','c']lst.append('d')lst.append(9)PRint lst #發現lst在末尾添加一個成員print type(lst) #lst類型為listprint type(lst[3]) #添加的9轉為str類型'''['a', 'b', 'c', 'd', 9]<type 'list'><type 'str'>'''#countlst.append('a') #添加aprint lst.count('a') #計數a個數,2#extend--在列表末尾一次性追加另一個序列的多個值a=[1,2,3]b=[4,5,6]a.extend(b) #將b列表添加到a列表,a列表被改變print a'''[1, 2, 3, 4, 5, 6]'''#index從列表中找出某個值第一個匹配的索引位置linux=['link','addr','bcast','mask','scope','addr']print linux.index('addr') #返回第一次索引到的位置print linux.index('mask') #索引是從0開始,對應索引3# print linux.index('home') #可以判斷在列表中是否存在某個值'''ValueError: 'home' is not in list[1, 2, 3, 4, 5, 6]13'''#insert將對象到列表中numbers=[1,3,4,5,7]numbers.insert(1,2)numbers.insert(5,'6')print numbers'''[1, 2, 3, 4, 5, '6', 7]'''#pop移除列表中的一個元素x=[1,2,3,4,5]x.pop() #類似棧,取出最頂端的print xx.pop(0) #取出0下標對應的索引值print x'''[1, 2, 3, 4][2, 3, 4]'''#remove移除列表中某個值的第一個匹配項y=['hello','boy','hello','girl']y.remove('hello') #此處移除第一個匹配的'hello'print y'''['boy', 'hello', 'girl']'''#reverse將列表的元素取反存放z=[1,2,3,4,5]z.reverse()print z'''[5, 4, 3, 2, 1]'''#sort對列表進行排序w=[1,4,6,8,2,5,9]w.sort() #默認為升序print w'''[1, 2, 4, 5, 6, 8, 9]'''
新聞熱點
疑難解答