一、列表
举例说明列表的各种操作
person = ["p1","p2","p3","p4","p5","p6","p7","p8","p9","p10"] person2 = [1,2,3,4] print(person[0],person[2]) #取出p1,p3 print(person[0:4]) #顾头不顾尾:列表里从零开始数,取出第0、1、2、3,四个值,第4不取,也即p5不取 print(person[5:8]) #顾头不顾尾:列表里从零开始数,取第5、6、7 print(person[-1]) #取列表中最后一个值 print(person[-5:]) #取列表中最后五个值
print(person[0:-1:2])#从第一个值开始,隔一个一取
print(person.index("p6")) #取p6的位置
print(person[person.index("p6")]) print(person.count("p7")) #该值在列表中的数量''' person.clear() #清空列表 person.reverse() #翻转列表中的值 person.sort() #给列表中的值排序 person.extend(person2) #合并person和person2,并不删除person2 del person2 #删掉列表 person.append("zhuijia") #追加到列表中的最后 person.insert(2,"charu") #插入到列表中2的位置 person[5] = ("xiugai") #修改位置5的值 person.remove("p7") #删除该值 del person[7] #删除该位置7的值 person.pop() #删除列表中最后一个值 person.pop(1) #删除该位置1的值 print(person) print(person2)
浅copy
person = ["p1","p2","p3","p4","p5","p6","p7",["salary",1000],"p8","p9","p10"] person2 = person.copy() #浅copy,只copy第一层,子列表不copy
person3 = person[:] #第二种方式
person4 = list(person) #第三种方式 person[3] = "zhongwen" person[7][0]="Salary" print(person) print(person2) 结果: ['p1', 'p2', 'p3', 'zhongwen', 'p5', 'p6', 'p7', ['Salary', 1000], 'p8', 'p9', 'p10'] ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', ['Salary', 1000], 'p8', 'p9', 'p10']
深copy
import copy person = ["p1","p2","p3","p4","p5","p6","p7",["salary",1000],"p8","p9","p10"] #person2 = person.copy() #浅copy,只copy第一层,子列表不copy person2 = copy.deepcopy(person) #深copy,所有都copy person[3] = "zhongwen" person[7][0]="Salary" print(person) print(person2) 结果: ['p1', 'p2', 'p3', 'zhongwen', 'p5', 'p6', 'p7', ['Salary', 1000], 'p8', 'p9', 'p10'] ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', ['salary', 1000], 'p8', 'p9', 'p10']
列表循环
person = ["p1","p2","p3","p4","p5","p6","p7",["salary",1000],"p8","p9","p10"] for i in person: print(i) 结果: p1 p2 p3 p4 p5 p6 p7 ['salary', 1000] p8 p9 p10
二、元组
元组其实跟列表差不多,也是存一组数,只不过它一旦被创建,便不能在修改,所以又叫只读列表
它只有两个方法一个是count,一个是index
person = ("p1","p2","p3","p4","p5","p6","p7","p8","p9","p10") person2 = ("o1","o2","o3","o4") print(person[0],person[2]) #取出p1,p3 print(person[0:4]) #顾头不顾尾:列表里从零开始数,取出第0、1、2、3,四个值,第4不取,也即p5不取 print(person[5:8]) #顾头不顾尾:列表里从零开始数,取第5、6、7 print(person[-1]) #取列表中最后一个值 print(person[-5:]) #取列表中最后五个值 print(person.index("p6")) #取p6的位置 print(person[person.index("p6")]) print(person.count("p7")) #该值在列表中的数量 del person2 #删掉列表 #列表循环 for i in person: print(i)