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 相关文章推荐
python判断给定的字符串是否是有效日期的方法
May 13 Python
介绍Python中的fabs()方法的使用
May 14 Python
Python使用Beautiful Soup包编写爬虫时的一些关键点
Jan 20 Python
python itchat实现微信自动回复的示例代码
Aug 14 Python
python交互式图形编程实例(一)
Nov 17 Python
django实现用户登陆功能详解
Dec 11 Python
浅谈django model postgres的json字段编码问题
Jan 05 Python
python 除法保留两位小数点的方法
Jul 16 Python
Django中密码的加密、验密、解密操作
Dec 19 Python
Django接收照片储存文件的实例代码
Mar 07 Python
详解python环境安装selenium和手动下载安装selenium的方法
Mar 17 Python
利用scikitlearn画ROC曲线实例
Jul 02 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+mysql留言本源码
2009/11/11 PHP
PHP管理内存函数 memory_get_usage()使用介绍
2012/09/23 PHP
PHP随机生成信用卡卡号的方法
2015/03/23 PHP
PHP合并数组函数array_merge用法分析
2017/02/17 PHP
Laravel中日期时间处理包Carbon的简单使用
2017/09/21 PHP
用jquery实现下拉菜单效果的代码
2010/07/25 Javascript
javascript内置对象arguments详解
2014/03/16 Javascript
JS 实现列表与多选框选择附预览动画
2014/10/29 Javascript
js实现类似于add(1)(2)(3)调用方式的方法
2015/03/04 Javascript
JS常用知识点整理
2017/01/21 Javascript
jQuery给表格添加分页效果
2017/03/02 Javascript
jQuery插件HighCharts绘制的基本折线图效果示例【附demo源码下载】
2017/03/07 Javascript
微信公众号菜单配置微信小程序实例详解
2017/03/31 Javascript
详解Angular 4 表单快速入门
2017/06/05 Javascript
微信小程序实现点击按钮移动view标签的位置功能示例【附demo源码下载】
2017/12/06 Javascript
使用vue-router切换页面时实现设置过渡动画
2019/10/31 Javascript
js实现有趣的倒计时效果
2021/01/19 Javascript
使用Python生成随机密码的示例分享
2016/02/18 Python
Python对多属性的重复数据去重实例
2018/04/18 Python
Python解析、提取url关键字的实例详解
2018/12/17 Python
详解一种用django_cache实现分布式锁的方式
2019/09/01 Python
Python爬虫使用浏览器cookies:browsercookie过程解析
2019/10/22 Python
window7下的python2.7版本和python3.5版本的opencv-python安装过程
2019/10/24 Python
Python3+selenium实现cookie免密登录的示例代码
2020/03/18 Python
Python单元测试及unittest框架用法实例解析
2020/07/09 Python
python中最小二乘法详细讲解
2021/02/19 Python
应届生幼儿园求职信
2013/11/12 职场文书
关于赌博的检讨书
2014/01/08 职场文书
英语课前三分钟演讲稿(6篇)
2014/09/13 职场文书
党员教师个人对照检查材料范文
2014/09/25 职场文书
学校党委副书记个人对照检查材料思想汇报
2014/09/28 职场文书
元旦标语大全
2014/10/09 职场文书
工作失职检讨书
2015/01/26 职场文书
2015年安全保卫工作总结
2015/05/14 职场文书
如何写通讯稿
2015/07/22 职场文书
python如何进行基准测试
2021/04/26 Python