一、列表
作用:多个装备,多个爱好,多门课程,多个女朋友等
定义:[]内可以有多个任意类型的值,逗号分隔
以下是列表的常用操作:
1 l=[1,2,3] #l=list([1,2,3]) 2 # print(type(l)) 3 4 #pat1===》优先掌握部分 5 # 索引:l=[1,2,3,4,5] 6 print(l[0]) 7 # 切片 8 l=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘] 9 10 # print(l[1:5]) 11 # print(l[1:5:2]) 12 # print(l[2:5]) 13 # print(l[-1]) 14 15 16 #了解 17 # print(l[-1:-4]) 18 # print(l[-4:]) 19 # l=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘] 20 # print(l[-2:]) 21 22 # 追加 23 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 24 # hobbies.append(‘girls‘) 25 # print(hobbies) 26 27 # 删除 28 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 29 # x=hobbies.pop(1) #不是单纯的删除,是删除并且把删除的元素返回,我们可以用一个变量名去接收该返回值 30 # print(x) 31 # print(hobbies) 32 33 # x=hobbies.pop(0) 34 # print(x) 35 # 36 # x=hobbies.pop(0) 37 # print(x) 38 39 #队列:先进先出 40 queue_l=[] 41 #入队 42 # queue_l.append(‘first‘) 43 # queue_l.append(‘second‘) 44 # queue_l.append(‘third‘) 45 # print(queue_l) 46 #出队 47 # print(queue_l.pop(0)) 48 # print(queue_l.pop(0)) 49 # print(queue_l.pop(0)) 50 51 52 #堆栈:先进后出,后进先出 53 # l=[] 54 # #入栈 55 # l.append(‘first‘) 56 # l.append(‘second‘) 57 # l.append(‘third‘) 58 # #出栈 59 # print(l) 60 # print(l.pop()) 61 # print(l.pop()) 62 # print(l.pop()) 63 64 #了解 65 # del hobbies[1] #单纯的删除 66 # hobbies.remove(‘eat‘) #单纯的删除,并且是指定元素去删除 67 68 69 # 长度 70 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 71 # print(len(hobbies)) 72 73 # 包含in 74 # hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘] 75 # print(‘sleep‘ in hobbies) 76 77 # msg=‘hello world egon‘ 78 # print(‘egon‘ in msg) 79 80 81 ##pat2===》掌握部分 82 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘] 83 # hobbies.insert(1,‘walk‘) 84 # hobbies.insert(1,[‘walk1‘,‘walk2‘,‘walk3‘]) 85 # print(hobbies) 86 87 # print(hobbies.count(‘eat‘)) 88 # print(hobbies) 89 # hobbies.extend([‘walk1‘,‘walk2‘,‘walk3‘]) 90 # print(hobbies) 91 92 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘] 93 # print(hobbies.index(‘eat‘)) 94 95 96 #pat3===》了解部分 97 hobbies=[‘play‘,‘eat‘,‘sleep‘,‘study‘,‘eat‘,‘eat‘] 98 # hobbies.clear() 99 # print(hobbies) 100 101 # l=hobbies.copy() 102 # print(l) 103 104 # l=[1,2,3,4,5] 105 # l.reverse() 106 # print(l) 107 108 l=[100,9,-2,11,32] 109 l.sort(reverse=True) 110 print(l)