跟老齐学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中for循环的使用方法
May 14 Python
python高手之路python处理excel文件(方法汇总)
Jan 07 Python
python 遍历字符串(含汉字)实例详解
Apr 04 Python
TensorFlow安装及jupyter notebook配置方法
Sep 08 Python
python获取当前目录路径和上级路径的实例
Apr 26 Python
python去重,一个由dict组成的list的去重示例
Jan 21 Python
python实现LBP方法提取图像纹理特征实现分类的步骤
Jul 11 Python
Python 随机生成测试数据的模块:faker基本使用方法详解
Apr 09 Python
Python脚本如何在bilibili中查找弹幕发送者
Jun 04 Python
Python带参数的装饰器运行原理解析
Jun 09 Python
使用Keras中的ImageDataGenerator进行批次读图方式
Jun 17 Python
解决python便携版无法直接运行py文件的问题
Sep 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实现从ftp服务器上下载文件树到本地电脑的程序
2009/02/10 PHP
查找mysql字段中固定字符串并替换的几个方法
2012/09/23 PHP
php读取二进制流(C语言结构体struct数据文件)的深入解析
2013/06/13 PHP
php实现水仙花数示例分享
2014/04/03 PHP
laravel 框架配置404等异常页面
2019/01/07 PHP
thinkphp5框架实现的自定义扩展类操作示例
2019/05/16 PHP
使用Rancher在K8S上部署高性能PHP应用程序的教程
2020/07/10 PHP
JavaScript移除数组内重复元素的方法
2015/03/18 Javascript
AngularJS 遇到的小坑与技巧小结
2016/06/07 Javascript
Mac下安装vue
2018/04/11 Javascript
vue中使用element-ui进行表单验证的实例代码
2018/06/22 Javascript
浅谈React Event实现原理
2018/09/20 Javascript
fetch 如何实现请求数据
2018/12/20 Javascript
vue elementUI table 自定义表头和行合并的实例代码
2019/05/22 Javascript
Vue中Table组件行内右键菜单实现方法(基于 vue + AntDesign)
2019/11/21 Javascript
开发Node CLI构建微信小程序脚手架的示例
2020/03/27 Javascript
几个提升Python运行效率的方法之间的对比
2015/04/03 Python
你应该知道的python列表去重方法
2017/01/17 Python
django 外键model的互相读取方法
2018/12/15 Python
pandas数据集的端到端处理
2019/02/18 Python
简单了解python PEP的一些知识
2019/07/13 Python
python 并发编程 非阻塞IO模型原理解析
2019/08/20 Python
Python判断字符串是否为空和null方法实例
2020/04/26 Python
python打包生成so文件的实现
2020/10/30 Python
html5摇一摇代码优化包括DeviceMotionEvent等等
2014/09/01 HTML / CSS
Square Off美国/加拿大:世界上最聪明的国际象棋棋盘
2018/12/06 全球购物
复古服装:RetroStage
2019/05/10 全球购物
史上最全面的Java面试题汇总!
2015/02/03 面试题
大专生的学习自我评价
2013/12/04 职场文书
幼儿园实习自我鉴定
2013/12/15 职场文书
技校毕业生个人学习的自我评价
2014/02/21 职场文书
班风学风建设方案
2014/05/06 职场文书
学校开除通知书
2015/04/25 职场文书
python中sys模块的介绍与实例
2021/04/17 Python
常用的MongoDB查询语句的示例代码
2021/07/25 MongoDB
Go语言的协程上下文的几个方法和用法
2022/04/11 Golang