python列表基础操作

Python列表基本操作

记住一句话,叫做顾首不顾尾

首先我们来定义一个列表

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]

接下来,我们就对这个列表来进行一系列的操作

 

1、切片

取值,取第一个和第二个

print(name[0],name[1])
打印结果
jixuege dajiba

说明:

上面的0和1指的是小标,从左到右顺序就是从0开始一直到4

 

打印一个区间

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]

print(name[:2])
打印结果
['jixuege', 'dajiba']

打印最后一个
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
print(name[-1])
打印结果
youtianai

2、追加
比如说我想追加一个人进去
复制代码
复制代码
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.append("xiha")
print(name)
打印结果

['jixuege', 'xitong', 'dajiba', 'youhua', 'boduoye', 'cangjinkong', 'youtianai', 'xiha']
复制代码
复制代码

这个会追加到末尾

还有一种就是插入insert

复制代码
复制代码
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]

name.insert(2,"youhua")
print(name)
打印结果
['jixuege', 'dajiba', 'youhua', 'boduoye', 'cangjinkong', 'youtianai']
复制代码
复制代码
 

3、修改

直接修改即可

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name[2]="wuming"
print(name)
打印结果
['jixuege', 'dajiba', 'wuming', 'cangjinkong', 'youtianai']

 

4、删除

直接清空

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.clear()
print(name)
打印结果
[]
 
删除指定元素
复制代码
复制代码
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.remove("jixuege")
print(name)
打印结果

['dajiba', 'boduoye', 'cangjinkong', 'youtianai']
复制代码
复制代码

 

删除指定下标

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
del name[2]
print(name)
打印结果
['jixuege', 'dajiba', 'cangjinkong', 'youtianai']

不指定下标删除最后一个
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.pop()
print(name)
打印结果
['jixuege', 'dajiba', 'boduoye', 'cangjinkong']

指定下标
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.pop(1)
print(name)
打印结果
['jixuege', 'boduoye', 'cangjinkong', 'youtianai']
posted @ 2017-06-19 16:12  云养猫  阅读(428)  评论(0编辑  收藏  举报