跟老齐学Python之有容乃大的list(3)


Posted in Python onSeptember 15, 2014

对list的操作

向list中插入一个元素

前面有一个向list中追加元素的方法,那个追加是且只能是将新元素添加在list的最后一个。如:

>>> all_users = ["qiwsir","github"]
>>> all_users.append("io")
>>> all_users
['qiwsir', 'github', 'io']

从这个操作,就可以说明list是可以随时改变的。这种改变的含义只它的大小即所容纳元素的个数以及元素内容,可以随时直接修改,而不用进行转换。这和str有着很大的不同。对于str,就不能进行字符的追加。请看官要注意比较,这也是str和list的重要区别。

与list.append(x)类似,list.insert(i,x)也是对list元素的增加。只不过是可以在任何位置增加一个元素。

我特别引导列为看官要通过官方文档来理解:

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

这次就不翻译了。如果看不懂英语,怎么了解贵国呢?一定要硬着头皮看英语,不仅能够学好程序,更能...(此处省略两千字)

根据官方文档的说明,我们做下面的实验,请看官从实验中理解:

>>> all_users
['qiwsir', 'github', 'io']
>>> all_users.insert("python")   #list.insert(i,x),要求有两个参数,少了就报错
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)

>>> all_users.insert(0,"python")
>>> all_users
['python', 'qiwsir', 'github', 'io']

>>> all_users.insert(1,"http://")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io']

>>> length = len(all_users)
>>> length
5

>>> all_users.insert(length,"algorithm")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']

小结:

list.insert(i,x),将新的元素x 插入到原list中的list[i]前面
如果i==len(list),意思是在后面追加,就等同于list.append(x)
删除list中的元素

list中的元素,不仅能增加,还能被删除。删除list元素的方法有两个,它们分别是:

list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

我这里讲授python,有一个习惯,就是用学习物理的方法。如果看官当初物理没有学好,那么一定是没有用这种方法,或者你的老师没有用这种教学法。这种方法就是:自己先实验,然后总结规律。

先实验list.remove(x),注意看上面的描述。这是一个能够删除list元素的方法,同时上面说明告诉我们,如果x没有在list中,会报错。

>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']
>>> all_users.remove("http://")
>>> all_users    #的确是把"http://"删除了
['python', 'qiwsir', 'github', 'io', 'algorithm']

>>> all_users.remove("tianchao")    #原list中没有“tianchao”,要删除,就报错。
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

注意两点:

如果正确删除,不会有任何反馈。没有消息就是好消息。
如果所删除的内容不在list中,就报错。注意阅读报错信息:x not in list
看官是不是想到一个问题?如果能够在删除之前,先判断一下这个元素是不是在list中,在就删,不在就不删,不是更智能吗?

如果看官想到这里,就是在编程的旅程上一进步。python的确让我们这么做。

>>> all_users
['python', 'qiwsir', 'github', 'io', 'algorithm']
>>> "python" in all_users    #这里用in来判断一个元素是否在list中,在则返回True,否则返回False
True

>>> if "python" in all_users:
...   all_users.remove("python")
...   print all_users
... else:
...   print "'python' is not in all_users"
... 
['qiwsir', 'github', 'io', 'algorithm']   #删除了"python"元素

>>> if "python" in all_users:
...   all_users.remove("python")
...   print all_users
... else:
...   print "'python' is not in all_users"
... 
'python' is not in all_users    #因为已经删除了,所以就没有了。

上述代码,就是两段小程序,我是在交互模式中运行的,相当于小实验。

另外一个删除list.pop([i])会怎么样呢?看看文档,做做实验。

>>> all_users
['qiwsir', 'github', 'io', 'algorithm']
>>> all_users.pop()   #list.pop([i]),圆括号里面是[i],表示这个序号是可选的
'algorithm'       #如果不写,就如同这个操作,默认删除最后一个,并且将该结果返回

>>> all_users
['qiwsir', 'github', 'io']

>>> all_users.pop(1)    #指定删除编号为1的元素"github"
'github'

>>> all_users
['qiwsir', 'io']
>>> all_users.pop()
'io'

>>> all_users      #只有一个元素了,该元素编号是0
['qiwsir']
>>> all_users.pop(1)  #但是非要删除编号为1的元素,结果报错。注意看报错信息
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: pop index out of range   #删除索引超出范围,就是1不在list的编号范围之内

给看官留下一个思考题,如果要向前面那样,能不能事先判断一下要删除的编号是不是在list的长度范围(用len(list)获取长度)以内?然后进行删除或者不删除操作。

list是一个有意思的东西,内涵丰富。看来下一讲还要继续讲list。并且可能会做一个有意思的游戏。请期待。

Python 相关文章推荐
浅析Python中的多进程与多线程的使用
Apr 07 Python
使用Python写个小监控
Jan 27 Python
详解python字节码
Feb 07 Python
python更改已存在excel文件的方法
May 03 Python
Python设计模式之组合模式原理与用法实例分析
Jan 11 Python
对python中类的继承与方法重写介绍
Jan 20 Python
numpy库与pandas库axis=0,axis= 1轴的用法详解
May 27 Python
使用python远程操作linux过程解析
Dec 04 Python
Python基于yield遍历多个可迭代对象
Mar 12 Python
JupyterNotebook 输出窗口的显示效果调整实现
Sep 22 Python
Python 机器学习工具包SKlearn的安装与使用
May 14 Python
利用Matlab绘制各类特殊图形的实例代码
Jul 16 Python
跟老齐学Python之有容乃大的list(2)
Sep 15 #Python
跟老齐学Python之有容乃大的list(1)
Sep 14 #Python
跟老齐学Python之一个免费的实验室
Sep 14 #Python
跟老齐学Python之从if开始语句的征程
Sep 14 #Python
跟老齐学Python之眼花缭乱的运算符
Sep 14 #Python
跟老齐学Python之玩转字符串(3)
Sep 14 #Python
跟老齐学Python之玩转字符串(2)
Sep 14 #Python
You might like
dedecms 制作模板中使用的全局标记图文教程
2007/03/11 PHP
php cookie 登录验证示例代码
2009/03/16 PHP
解析csv数据导入mysql的方法
2013/07/01 PHP
php操作xml入门之xml基本介绍及xml标签元素
2015/01/23 PHP
PHP解密Unicode及Escape加密字符串
2015/05/17 PHP
表单的焦点顺序tabindex和对应enter键提交
2013/01/04 Javascript
如何创建一个JavaScript弹出DIV窗口层的效果
2013/09/25 Javascript
jquery上传插件fineuploader上传文件使用方法(jquery图片上传插件)
2013/12/05 Javascript
JS删除字符串中重复字符方法
2014/03/09 Javascript
jQuery防止click双击多次提交及传递动态函数或多参数
2014/04/02 Javascript
深入探究AngularJS框架中Scope对象的超级教程
2016/01/04 Javascript
javascript特效实现——当前时间和倒计时效果的简单实例
2016/07/20 Javascript
JS常用倒计时代码实例总结
2017/02/07 Javascript
Javascript中click与blur事件的顺序详析
2017/04/25 Javascript
在vue组件中使用axios的方法
2018/03/16 Javascript
简单的React SSR服务器渲染实现
2018/12/11 Javascript
JavaScript&quot;模拟事件&quot;的注意要点详解
2019/02/13 Javascript
Mpvue中使用Vant Weapp组件库的方法步骤
2019/05/16 Javascript
Vue 打包体积优化方案小结
2020/05/20 Javascript
vue.js实现h5机器人聊天(测试版)
2020/07/16 Javascript
vue 全局封装loading加载教程(全局监听)
2020/11/05 Javascript
[02:44]2014DOTA2 国际邀请赛中国区预选赛 大神红毯秀
2014/05/25 DOTA
python re库的正则表达式入门学习教程
2019/03/08 Python
python 中值滤波,椒盐去噪,图片增强实例
2019/12/18 Python
django的模型类管理器——数据库操作的封装详解
2020/04/01 Python
Keras 中Leaky ReLU等高级激活函数的用法
2020/07/05 Python
python 实时调取摄像头的示例代码
2020/11/25 Python
HTML5操作WebSQL数据库的实例代码
2017/08/26 HTML / CSS
Html5导航栏吸顶方案原理与对比实现
2020/06/10 HTML / CSS
Paul’s Boutique官网:英国时尚手袋品牌
2018/03/31 全球购物
《鸟岛》教学反思
2014/04/26 职场文书
法人身份证明书
2014/10/08 职场文书
查摆问题整改措施范文
2014/10/11 职场文书
通讯稿格式及范文
2015/07/22 职场文书
CentOS 7安装mysql5.7使用XtraBackUp备份工具命令详解
2022/04/12 MySQL
Nginx的gzip相关介绍
2022/05/11 Servers