码迷,mamicode.com
首页 > 编程语言 > 详细

python列表基础操作

时间:2017-06-19 16:24:30      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:说明   span   技术分享   rem   python列表   img   下标   定义   move   

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‘]

python列表基础操作

标签:说明   span   技术分享   rem   python列表   img   下标   定义   move   

原文地址:http://www.cnblogs.com/chenqizhou/p/7049178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!