Python中list列表的一些进阶使用方法介绍


Posted in Python onAugust 15, 2015

判断一个 list 是否为空

传统的方式:

if len(mylist):
  # Do something with my list
else:
  # The list is empty

由于一个空 list 本身等同于 False,所以可以直接:

if mylist:
  # Do something with my list
else:
  # The list is empty

遍历 list 的同时获取索引

传统的方式:

i = 0
for element in mylist:
  # Do something with i and element
  i += 1

这样更简洁些:

for i, element in enumerate(mylist):
  # Do something with i and element
  pass

list 排序

在包含某元素的列表中依据某个属性排序是一个很常见的操作。例如这里我们先创建一个包含 person 的 list:

class Person(object):
  def __init__(self, age):
    self.age = age

persons = [Person(age) for age in (14, 78, 42)]

传统的方式是:

def get_sort_key(element):
  return element.age

for element in sorted(persons, key=get_sort_key):
  print "Age:", element.age

更加简洁、可读性更好的方法是使用 Python 标准库中的 operator 模块:

from operator import attrgetter

for element in sorted(persons, key=attrgetter('age')):
  print "Age:", element.age

attrgetter 方法优先返回读取的属性值作为参数传递给 sorted 方法。operator 模块还包括 itemgetter 和 methodcaller 方法,作用如其字面含义。

list解析

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')]
Python 相关文章推荐
关于Tensorflow中的tf.train.batch函数的使用
Apr 24 Python
python实现机器学习之多元线性回归
Sep 06 Python
详解Python匿名函数(lambda函数)
Apr 19 Python
PyTorch的Optimizer训练工具的实现
Aug 18 Python
python 函数嵌套及多函数共同运行知识点讲解
Mar 03 Python
python 工具 字符串转numpy浮点数组的实现
Mar 14 Python
Python闭包及装饰器运行原理解析
Jun 17 Python
Win10下用Anaconda安装TensorFlow(图文教程)
Jun 18 Python
Python容器类型公共方法总结
Aug 19 Python
python opencv pytesseract 验证码识别的实现
Aug 28 Python
Python脚本调试工具安装过程
Jan 11 Python
python3实现无权最短路径的方法
May 12 Python
Python中的super()方法使用简介
Aug 14 #Python
在Python中使用正则表达式的方法
Aug 13 #Python
简单讲解Python中的闭包
Aug 11 #Python
Python实现短网址ShortUrl的Hash运算实例讲解
Aug 10 #Python
python实现web方式logview的方法
Aug 10 #Python
python实现JAVA源代码从ANSI到UTF-8的批量转换方法
Aug 10 #Python
python用10行代码实现对黄色图片的检测功能
Aug 10 #Python
You might like
如何用PHP实现插入排序?
2013/04/10 PHP
PHP中Fatal error session_start()错误解决步骤
2014/08/05 PHP
PHP中Http协议post请求参数
2015/11/02 PHP
在php中设置session用memcache来存储的方法总结
2016/01/14 PHP
PHP实现打包zip并下载功能
2018/06/12 PHP
获取任意Html元素与body之间的偏移距离 offsetTop、offsetLeft (For:IE5+ FF1 )[
2006/12/22 Javascript
JavaScript中的值是按值传递还是按引用传递问题探讨
2015/01/30 Javascript
JS中产生标识符方式的演变
2015/06/12 Javascript
基于jQuery实现简单的折叠菜单效果
2015/11/23 Javascript
node网页分段渲染详解
2016/09/05 Javascript
jQuery实现圣诞节礼物动画案例解析
2016/12/25 Javascript
简单好用的nodejs 爬虫框架分享
2017/03/26 NodeJs
详解Vue.js Mixins 混入使用
2017/09/15 Javascript
百度地图去掉marker覆盖物或者去掉maker的label文字方法
2018/01/26 Javascript
nodejs+mongodb aggregate级联查询操作示例
2018/03/17 NodeJs
ES6的Fetch异步请求的实现方法
2018/12/07 Javascript
JavaScript数组去重的几种方法
2019/04/07 Javascript
react quill中图片上传由默认转成base64改成上传到服务器的方法
2019/10/30 Javascript
Vue组件间的通信pubsub-js实现步骤解析
2020/03/11 Javascript
Element Breadcrumb 面包屑的使用方法
2020/07/26 Javascript
python中os操作文件及文件路径实例汇总
2015/01/15 Python
Django重装mysql后启动报错:No module named ‘MySQLdb’的解决方法
2018/04/22 Python
浅谈Python基础—判断和循环
2019/03/22 Python
Python 安装第三方库 pip install 安装慢安装不上的解决办法
2019/06/18 Python
python 中pyqt5 树节点点击实现多窗口切换问题
2019/07/04 Python
Python 正则表达式爬虫使用案例解析
2019/09/23 Python
Python脚本实现Zabbix多行日志监控过程解析
2020/08/26 Python
Django项目创建及管理实现流程详解
2020/10/13 Python
天美时手表加拿大官网:Timex加拿大
2016/09/01 全球购物
如何处理简单的PHP错误
2015/10/14 面试题
舞蹈兴趣小组活动总结
2014/07/07 职场文书
公司副总经理岗位职责
2014/10/01 职场文书
关于童年的读书笔记
2015/06/26 职场文书
Python利用folium实现地图可视化
2021/05/23 Python
python实现简易自习室座位预约系统
2021/06/30 Python
为了顺利买到演唱会的票用Python制作了自动抢票的脚本
2021/10/16 Python