列表增删改查方法
#_author:Administrator
#date:2019/10/24
#列表List
#增删改查
#增 *1 切片
a=['xiaowwang','xiaohuang','xiaozhang','xiaodu','aming']
print(a[4]) #aming
print(a[1:]) #['xiaohuang', 'xiaozhang', 'xiaodu', 'aming'],取到最后一个
print(a[1:-1])# ['xiaohuang', 'xiaozhang', 'xiaodu'],取到倒数第二个,所以-1为最后一个元素
print(a[1:-1:2])#['xiaohuang', 'xiaodu'],从左到右隔一个去取
print(a[1::2])#['xiaohuang', 'xiaodu'],从左到右隔一个去取
print(a[3::-2])#从右到左隔一个去取,将上一行两个值调换位置,['xiaodu', 'xiaohuang'],3代表索引为3的位置
print("-----------------------")
print(a[-2::-1])#'xiaodu', 'xiaozhang', 'xiaohuang', 'xiaowwang']从倒数第二个元素开始
#*2.添加 append(默认插到最后一个位置)
#insert(将数据插入到任意一个位置)
a.append("star")
print(a)#['xiaowwang', 'xiaohuang', 'xiaozhang', 'xiaodu', 'aming', 'star']
a.insert(1,'lihua')
print(a)#['xiaowwang', 'lihua', 'xiaohuang', 'xiaozhang', 'xiaodu', 'aming', 'star']
a[1]='xingxing'
print(a)#['xiaowwang', 'xingxing', 'xiaohuang', 'xiaozhang', 'xiaodu', 'aming', 'star']第二个位置变为xingxing
a[1:3]=['a','b']#用a,b将原来两个位置的值替换
print(a) #['xiaowwang', 'a', 'b', 'xiaozhang', 'xiaodu', 'aming', 'star']
#3删除
#(1)删除第一种方法
a.remove('xiaowwang')
print(a)# ['a', 'b', 'xiaozhang', 'xiaodu', 'aming', 'star']
#(2)删除第二种方法
c=a.pop(1)#删除第一个位置
#print(a)#['a', 'xiaozhang', 'xiaodu', 'aming', 'star']
print(c)#b
#(3)删除第三种方法
del a[1]
print(a)#['a', 'xiaodu', 'aming', 'star']
Output:
ming
['xiaohuang', 'xiaozhang', 'xiaodu', 'aming']
['xiaohuang', 'xiaozhang', 'xiaodu']
['xiaohuang', 'xiaodu']
['xiaohuang', 'xiaodu']
['xiaodu', 'xiaohuang']
-----------------------
['xiaodu', 'xiaozhang', 'xiaohuang', 'xiaowwang']
['xiaowwang', 'xiaohuang', 'xiaozhang', 'xiaodu', 'aming', 'star']
['xiaowwang', 'lihua', 'xiaohuang', 'xiaozhang', 'xiaodu', 'aming', 'star']
['xiaowwang', 'xingxing', 'xiaohuang', 'xiaozhang', 'xiaodu', 'aming', 'star']
['xiaowwang', 'a', 'b', 'xiaozhang', 'xiaodu', 'aming', 'star']
['a', 'b', 'xiaozhang', 'xiaodu', 'aming', 'star']
b
['a', 'xiaodu', 'aming', 'star']
进程已结束,退出代码0