首页 > 代码库 > Python List

Python List

 1 #!/usr/bin/env python 2 #-*-coding:utf-8 -*- 3 #创建列表list 4 li = [a,1,2,3,(4,5)] 5 #li=list(iterator) 6 print(li) 7 #通过下标获取列表元素数据 0开始 8 print(li[0]) 9 #切片包含上限索引,不包含下限索引10 print(li[1:3]) #[1, 2]11 #如果上限索引为0,可以省略12 #下限索引为list长度,也可以省略13 print(li[:3])  #[‘a‘, 1, 2]14 print(li[3:])  #[3, (4, 5)]15 #全部元素16 print(li[:])17 #负数索引,从尾部开始向前计数来取元素18 print(li[-1])  #(4, 5)19 print("*******************************************")20 #增加元素21 print(li)             #[‘a‘, 1, 2, 3, (4, 5)]22 #append 末尾追加单个元素--iter,list,tuple,dict,str,int,float23 li.append({1:"new"})      #[‘a‘, 1, 2, 3, (4, 5), ‘new‘]24 print(li)25 #在索引点插入元素26 li.insert(2,"old")    #[‘a‘, 1, ‘old‘, 2, 3, (4, 5), ‘new‘]27 print(li)28 #连接list29 li.extend(["two","elem"]) #[‘a‘, 1, ‘old‘, 2, 3, (4, 5), ‘new‘, ‘two‘, ‘elem‘]30 print (li)31 print("-----extend and append diff------")32 li = [a,b,c]33 #extend 接受参数为iter34 li.extend(("d","e","f")) #[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]35 print(li)36 li = [a,b,c]37 li.append([d,e,f]) #[‘a‘, ‘b‘, ‘c‘, [‘d‘, ‘e‘, ‘f‘]]38 print(li)39 print("*******************************************")40 li = li + ["example","new"] # + => extend41 print(li)42 print("*******************************************")43 #查找,首次出现并返回索引值44 li += ["old","new"] 45 print(li)46 print(li.index("new"))47 print("*******************************************")48 #remove 删除 del list[i],list.remove(key)49 print(li) #[‘a‘, ‘b‘, ‘c‘, [‘d‘, ‘e‘, ‘f‘], ‘example‘, ‘new‘, ‘old‘, ‘new‘]50 #remove 匹配第一个元素51 li.remove("new") #[‘a‘, ‘b‘, ‘c‘, [‘d‘, ‘e‘, ‘f‘], ‘example‘, ‘old‘, ‘new‘]52 print(li) 53 #pop 删除最后个元素,并且返回元素的值54 print(li.pop()) #new55 print(li) #[‘a‘, ‘b‘, ‘c‘, [‘d‘, ‘e‘, ‘f‘], ‘example‘, ‘old‘]56 #del删除索引位置的元素57 del li[3] #[‘d‘, ‘e‘, ‘f‘],58 print(li) #[‘a‘, ‘b‘, ‘c‘, ‘example‘, ‘old‘]59 print("*******************************************")60 li = list((a,1,2,3,(4,5)))61 it = iter(li)62 print(it.next())63 ll = list(it) #调用it.next()64 print(ll)

 

Python List