Python 基础——列表之增、删、改、查及插

列表

1.增 append

1 names = ["a","b","c","d"]#称为列表,类似数组
2 print(names)
3 names.append("e")
4 print(names)

 


2.删 remove  del   pop()

1 names = ["a","b","c","d"]#称为列表,类似数组
2 print(names)
3 #删  三种方法
4 names.remove("a")   # 法一:remove,直接写上要删除的语句
5 #del names[0]       #法二:del 删除某元素
6 #names.pop()        #法三:pop  若无索引,则默认删除最后一个元素
7 #names.pop(3)       #pop() 括号里写上索引,则对应的元素
8 print(names)

 


3.改 

1 names = ["a","b","c","d"]#称为列表,类似数组,其索引是从0数起
2 print(names)
3 #
4 names[2] = "f"  #想改谁,就直接将元素写在对应的索引处
5 print(names)

 


 4.index 查找的就是它的索引

1 names = ["a","b","c","d","e","g"]#称为列表,类似数组
2 print(names)
3 #如果列表有很多元素,查找某个元素,并打印出来
4 print(names.index("d"))     #找到它的位置
5 print(names[names.index("g")])  #找到后打印出来

 

 

 5.插 insert  在列表中随意的插入一个元素 

1 names = ["a","b","c","d","e","g"]#称为列表,类似数组
2 print(names)
3 #插  insert
4 names.insert(1,"H")   #括号的第一个是要插入的位置,后面是要插入的元素
5 print(names)
6 names.insert(3,"h")   #括号的第一个是要插入的位置,后面是要插入的元素
7 print(names)

 


 2019-08-28   21:58:10

 

 

 

 

 

 

 

 

posted on 2019-08-28 22:01  GRIT_风  阅读(299)  评论(0)    收藏  举报