跟老齐学Python之再深点,更懂list


Posted in Python onSeptember 20, 2014

list解析

先看下面的例子,这个例子是想得到1到9的每个整数的平方,并且将结果放在list中打印出来

>>> power2 = []
>>> for i in range(1,10):
...   power2.append(i*i)
... 
>>> power2
[1, 4, 9, 16, 25, 36, 49, 64, 81]

python有一个非常有意思的功能,就是list解析,就是这样的:

>>> squares = [x**2 for x in range(1,10)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81]

看到这个结果,看官还不惊叹吗?这就是python,追求简洁优雅的python!

其官方文档中有这样一段描述,道出了list解析的真谛:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

还记得前面一讲中的那个问题吗?

找出100以内的能够被3整除的正整数。
我们用的方法是:

aliquot = []

for n in range(1,100):
  if n%3 == 0:
    aliquot.append(n)

print aliquot

好了。现在用list解析重写,会是这样的:

>>> aliquot = [n for n in range(1,100) if n%3==0]
>>> aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

震撼了。绝对牛X!

其实,不仅仅对数字组成的list,所有的都可以如此操作。请在平复了激动的心之后,默默地看下面的代码,感悟一下list解析的魅力。

>>> mybag = [' glass',' apple','green leaf ']  #有的前面有空格,有的后面有空格
>>> [one.strip() for one in mybag]       #去掉元素前后的空格
['glass', 'apple', 'green leaf']
enumerate

这是一个有意思的内置函数,本来我们可以通过for i in range(len(list))的方式得到一个list的每个元素编号,然后在用list[i]的方式得到该元素。如果要同时得到元素编号和元素怎么办?就是这样了:

>>> for i in range(len(week)):
...   print week[i]+' is '+str(i)   #注意,i是int类型,如果和前面的用+连接,必须是str类型
... 
monday is 0
sunday is 1
friday is 2

python中提供了一个内置函数enumerate,能够实现类似的功能

>>> for (i,day) in enumerate(week):
...   print day+' is '+str(i)
... 
monday is 0
sunday is 1
friday is 2

算是一个有意思的内置函数了,主要是提供一个简单快捷的方法。

官方文档是这么说的:

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

顺便抄录几个例子,供看官欣赏,最好实验一下。
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

在这里有类似(0,'Spring')这样的东西,这是另外一种数据类型,待后面详解。

Python 相关文章推荐
python双向链表实现实例代码
Nov 21 Python
python搭建虚拟环境的步骤详解
Sep 27 Python
Python基础知识_浅谈用户交互
May 31 Python
python微信跳一跳系列之色块轮廓定位棋盘
Feb 26 Python
python同时遍历数组的索引和值的实例
Nov 15 Python
Python常见数字运算操作实例小结
Mar 22 Python
python和c语言的主要区别总结
Jul 07 Python
pow在python中的含义及用法
Jul 11 Python
python redis连接 有序集合去重的代码
Aug 04 Python
解决torch.autograd.backward中的参数问题
Jan 07 Python
Python脚本导出为exe程序的方法
Mar 25 Python
安装python依赖包psycopg2来调用postgresql的操作
Jan 01 Python
跟老齐学Python之画圈还不简单吗?
Sep 20 #Python
跟老齐学Python之list和str比较
Sep 20 #Python
Python显示进度条的方法
Sep 20 #Python
python中对list去重的多种方法
Sep 18 #Python
Python中用Descriptor实现类级属性(Property)详解
Sep 18 #Python
Python中的闭包总结
Sep 18 #Python
python的即时标记项目练习笔记
Sep 18 #Python
You might like
PHP中文件上传的一个问题
2010/09/04 PHP
ThinkPHP模板判断输出Empty标签用法详解
2014/06/30 PHP
TP - 比RBAC更好的权限认证方式(Auth类认证)
2021/03/09 PHP
Javascript 构造函数 实例分析
2008/11/26 Javascript
实现JavaScript中继承的三种方式
2009/10/16 Javascript
JavaScript开发规范要求(规范化代码)
2010/08/16 Javascript
基于JavaScript实现继承机制之原型链(prototype chaining)的详解
2013/05/07 Javascript
jQuery实现dialog设置focus焦点的方法
2015/06/10 Javascript
gameboy网页闯关游戏(riddle webgame)--仿微信聊天的前端页面设计和难点
2016/02/21 Javascript
jQuery实现鼠标滚动图片延迟加载效果附源码下载
2016/06/28 Javascript
Vue 中对图片地址进行拼接的方法
2018/09/03 Javascript
小程序实现投票进度条
2019/11/20 Javascript
Vuex的API文档说明详解
2020/02/05 Javascript
JavaScript利用键盘码控制div移动
2020/03/19 Javascript
viewer.js一个强大的基于jQuery的图像查看插件(支持旋转、缩放)
2020/04/01 jQuery
Openlayers学习之加载鹰眼控件
2020/09/28 Javascript
python实现从一组颜色中找出与给定颜色最接近颜色的方法
2015/03/19 Python
python开发之文件操作用法实例
2015/11/13 Python
Python实现的归并排序算法示例
2017/11/21 Python
python生成lmdb格式的文件实例
2018/11/08 Python
python使用PIL模块获取图片像素点的方法
2019/01/08 Python
Python设计模式之代理模式实例详解
2019/01/19 Python
简单了解Python matplotlib线的属性
2019/06/29 Python
Python Http请求json解析库用法解析
2020/11/28 Python
python3中数组逆序输出方法
2020/12/01 Python
实例讲解CSS3中的border-radius属性
2015/08/18 HTML / CSS
法国隐形眼镜网站:VisionDirect.fr
2020/03/03 全球购物
奥地利手表、香水、化妆品和珠宝购物网站:Brasty.at
2021/01/17 全球购物
触发器(trigger)的功能都有哪些?写出一个触发器的例子
2012/09/17 面试题
文员自我评价怎么写
2013/09/19 职场文书
财务管理专业毕业生求职信范文
2013/09/21 职场文书
会计电算一体化个人简历的自我评价
2013/10/15 职场文书
2015年专项整治工作总结
2015/04/03 职场文书
个人廉政承诺书
2015/04/28 职场文书
2015年党员发展工作总结
2015/05/13 职场文书
Python基础之变量的相关知识总结
2021/06/23 Python