跟老齐学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中的super用法详解
May 28 Python
python构建自定义回调函数详解
Jun 20 Python
pandas groupby 分组取每组的前几行记录方法
Apr 20 Python
python实现字符串和字典的转换
Sep 29 Python
Python小工具之消耗系统指定大小内存的方法
Dec 03 Python
Python进阶之@property动态属性的实现
Apr 01 Python
pyqt5对用qt designer设计的窗体实现弹出子窗口的示例
Jun 19 Python
python爬虫的一个常见简单js反爬详解
Jul 09 Python
django页面跳转问题及注意事项
Jul 18 Python
python装饰器的特性原理详解
Dec 25 Python
Python序列化pickle模块使用详解
Mar 05 Python
pycharm中如何自定义设置通过“ctrl+滚轮”进行放大和缩小实现方法
Sep 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
Body是什么,该怎么喝出咖啡里的口感
2021/03/03 咖啡文化
php中file_get_contents与curl性能比较分析
2014/11/08 PHP
PHP连接access数据库
2015/03/27 PHP
Laravel 5框架学习之路由、控制器和视图简介
2015/04/07 PHP
laravel 数据迁移与 Eloquent ORM的实现方法
2019/04/12 PHP
一直复略了的一个问题,关于表单重复提交
2007/02/15 Javascript
javascript 获取图片颜色
2009/04/05 Javascript
js实现运动logo图片效果及运动元素对象sportBox使用方法
2012/12/25 Javascript
JS实现一键回顶功能示例代码
2013/10/28 Javascript
javascript实现删除前弹出确认框
2015/06/04 Javascript
举例讲解JavaScript substring()的使用方法
2015/11/09 Javascript
基于jQuery实现中英文切换导航条效果
2016/09/18 Javascript
vue.js将unix时间戳转换为自定义时间格式
2017/01/03 Javascript
关于Sequelize连接查询时inlude中model和association的区别详解
2017/02/27 Javascript
使用jQuery的load方法设计动态加载及解决被加载页面js失效问题
2017/03/01 Javascript
nodejs搭建本地服务器并访问文件的方法
2017/03/03 NodeJs
详解JavaScript对象的深浅复制
2017/03/30 Javascript
vue2.0+vue-dplayer实现hls播放的示例
2018/03/02 Javascript
jquery获取file表单选择文件的路径、名字、大小、类型
2019/01/18 jQuery
原生JavaScript创建不可变对象的方法简单示例
2020/05/07 Javascript
React实现轮播效果
2020/08/25 Javascript
Python实现约瑟夫环问题的方法
2016/05/03 Python
Python多线程爬虫实战_爬取糗事百科段子的实例
2017/12/15 Python
python3实现SMTP发送邮件详细教程
2018/06/19 Python
Python 确定多项式拟合/回归的阶数实例
2018/12/29 Python
Python 取numpy数组的某几行某几列方法
2019/10/24 Python
matplotlib 对坐标的控制,加图例注释的操作
2020/04/17 Python
Python使用Excel将数据写入多个sheet
2020/05/16 Python
Python logging模块进行封装实现原理解析
2020/08/07 Python
Vita Fede官网:在意大利手工制作,在纽约市设计
2019/10/25 全球购物
IGK Hair官网:喷雾、洗发水、护发素等
2020/11/03 全球购物
初入社会应届生求职信
2013/11/18 职场文书
《老山界》教学反思
2014/04/08 职场文书
烟台的海导游词
2015/02/02 职场文书
离婚民事起诉状
2015/08/03 职场文书
2016大学生暑期三下乡心得体会
2016/01/23 职场文书