第五節 列表&元組
阿新 • • 發佈:2018-03-21
import body 修改 不包含 sort 插入 xiang 大寫 jin #edit by weiwei xu
names=["xww","wangyu","yujunxiang","shaolun"]
names.append("zhuijia")#追加到表最後
names.insert(1,"charu")#1,代表插入到1這個位置
names[0]="xiugai"#將xww改為xiugai,直接在位置重新賦值
print(names[2])#從0開始第2個
print(names[1:3])#顧頭不顧尾,包含1,不包含3,取1,2
print(names[-1])#從後往前取
print(names[-2:-1])
print(names[-2:])#從-2開始取到最後
print(names)
#delete
names.remove("wangyu")#刪除
#del names[2]#刪除2位置數據
#names.pop(2)#刪除2位置數據,默認刪除最後一個數據
print(names)
print(names.index("charu"))#查找charu所在的位置
print(names[names.index("charu")])#找到並打印
names.append("zhuijia")
print(names.count("zhuijia"))#查找有幾個zhuijia
names.reverse()#前後顛倒
#names.clear()#清除
names.sort()#排序,按照特殊符號、數字、大寫、小寫
print(names)
names2=[1,2,3,4,5,6,7]
names.extend(names2)#兩表合並
del names2#刪除 表2
print(names)
淺copy
#edit by weiwei xu
#utf-8-
names=["xww","yujunxiang","wangzhuzhu",["haha","shamao","二楞"],"wuyeqing","luojinxin"]
name2=names.copy()#淺copy,從結果可以看到,name2裏的wangzhuzhu沒變,但二哈變了(如果開始引用了copy,import copy,此處也可以寫成 name2=copy.copy(names))
print(names)
print(name2)
names[2]="dage"
names[3][0]="二哈"
print(names)
print(name2)
print(names[0:-1:2])#正常情況下0和-1可以省略,可以寫成print(::2),從0開始到最後,每隔2個打印
for i in names: #打印列表
print(i)
列表,元組
‘‘‘
name = ["alex","tenglan","eric","rai","tom","amy"]
print(name)
print(name[1:4])#取1-4之間的數據,不包括第4個
print(name[1:-1])
print(name[:3])
print(name[3:])#後面不寫-1,就可以取到最後的值
print(name[0:-1:2])
print(name[::2])#同上面效果一樣,0和-1可以不寫
name.append("new_student")#追加到最後
print(name)
name.insert(2,‘強行插入‘) #在2的位置插入數據
print(name)
name[2]=‘換新人了‘#修改
print(name)
del name[2]#刪除某列
print(name)
name.remove(‘tenglan‘)#刪除特定值的列
print(name)
name.pop()#刪除列表最後一列
print(name)
names = [‘xww‘, ‘tenglan‘, ‘Eric‘,‘tom‘,‘amy‘,"tom"]
b = [1,2,3]
names.extend(b)#擴展
print(names)
name_copy =names.copy()#copy
print(name_copy)
print(names.count("tom"))#統計tom的數量
names.remove(1)
names.remove(2)
names.remove(3)
‘‘‘
names = [‘xww‘, ‘tenglan‘, ‘Eric‘,‘tom‘,‘amy‘]
print(names.index("Eric"))#獲取列的下標
print(names)
names.sort()#排序完畢後打印原來的值
print(names)
names.reverse()#翻轉排序
print(names)
namexx = ("xww","wangsong","kill","piapia")#元組,是只讀文件,無法修改,
ddd=namexx.count("xww")#匯總xww數量
ttt=namexx.index("kill")#查看kill的下標
print(ddd)
print(ttt)
第五節 列表&元組