# 作者 : liuxing # 日期 : 2017-12-25 # list用法 增删改查 names=["liuxing","wangnian","sunkang","xiaohang","zhujian","xuxian"] #----------- 查------------- print("names->",names) print("names[1]->",names[1]) print("names[1:]->",names[1:]) print("names[:-1]->",names[:-1]) print("names[1:-1]->",names[1:-1]) print("names[1:-1:2]->",names[1:-1:2]) print("names[1::2]->",names[1::2]) print("names[::2]->",names[::2]) print("names[1::-1]->",names[1::-1]) #------------增--------------- names.append("ligang") #添加到列表尾部 print("append->",names) names.insert(1,"wangqiang") #添加到任意位置 print("insert->",names) #------------改--------------- names[0]="xiongda" names[1:3]=["baoqiang","jiangwen"] #------------删--------------- names.remove("sunkang") print("remove->",names) name=names.pop(1) #pop可以有返回值 print("pop->",names) del names[2] print("del->",names)
结果: names-> [‘liuxing‘, ‘wangnian‘, ‘sunkang‘, ‘xiaohang‘, ‘zhujian‘, ‘xuxian‘] names[1]-> wangnian names[1:]-> [‘wangnian‘, ‘sunkang‘, ‘xiaohang‘, ‘zhujian‘, ‘xuxian‘] names[:-1]-> [‘liuxing‘, ‘wangnian‘, ‘sunkang‘, ‘xiaohang‘, ‘zhujian‘] names[1:-1]-> [‘wangnian‘, ‘sunkang‘, ‘xiaohang‘, ‘zhujian‘] names[1:-1:2]-> [‘wangnian‘, ‘xiaohang‘] names[1::2]-> [‘wangnian‘, ‘xiaohang‘, ‘xuxian‘] names[::2]-> [‘liuxing‘, ‘sunkang‘, ‘zhujian‘] names[1::-1]-> [‘wangnian‘, ‘liuxing‘] append-> [‘liuxing‘, ‘wangnian‘, ‘sunkang‘, ‘xiaohang‘, ‘zhujian‘, ‘xuxian‘, ‘ligang‘] insert-> [‘liuxing‘, ‘wangqiang‘, ‘wangnian‘, ‘sunkang‘, ‘xiaohang‘, ‘zhujian‘, ‘xuxian‘, ‘ligang‘] remove-> [‘xiongda‘, ‘baoqiang‘, ‘jiangwen‘, ‘xiaohang‘, ‘zhujian‘, ‘xuxian‘, ‘ligang‘] pop-> [‘xiongda‘, ‘jiangwen‘, ‘xiaohang‘, ‘zhujian‘, ‘xuxian‘, ‘ligang‘] del-> [‘xiongda‘, ‘jiangwen‘, ‘zhujian‘, ‘xuxian‘, ‘ligang‘]
时间: 2024-11-07 19:06:26