python中的列表推导浅析

来源:互联网 发布:seo外链工具有用吗? 编辑:程序博客网 时间:2024/05/17 01:50

python中的列表推导浅析

作者: 字体:[增加 减小] 类型:转载 时间:2014-04-26 我要评论

这篇文章主要介绍了python中的列表推导,需要的朋友可以参考下

列表推导(List comprehension)的作用是为了更方便地生成列表(list)。

比如,一个list变量的元素均为数字,如果需要将每个元素的值乘以2并生成另外一个list,下面是一种做法:

复制代码 代码如下:

#-*-encoding:utf-8-*-

list1 = [1,2,4,5,12]
list2 = []
for item in list1:
    list2.append(item*2)
print list2


如果使用列表推导,可以这样:
复制代码 代码如下:

#-*-encoding:utf-8-*-

list1 = [1,2,4,5,12]
list2 = [item*2 for item in list1 ]
print list2


可以通过if过滤掉不想要的元素,例如提取出list1中小于10的元素:
复制代码 代码如下:

#-*-encoding:utf-8-*-

list1 = [1,2,4,5,12]
list2 = [item for item in list1 if item < 10 ]
print list2


如果要将两个list中的元素进行组合,可以:
复制代码 代码如下:

#-*-encoding:utf-8-*-

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [(item1,item2) for item1 in list1 for item2 in list2 ]
print list3


官方文档中给出了一个比较复杂的转置矩阵的例子:
复制代码 代码如下:

#-*-encoding:utf-8-*-

matrix1 = [
          [1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12]
          ]
matrix2 = [[row[i] for row in matrix1] for i in range(4)]
for row in matrix2:
    print row


运行结果如下:
复制代码 代码如下:

[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
[4, 8, 12]

您可能感兴趣的文章:

  • Python中3种内建数据结构:列表、元组和字典
  • Python 列表list使用介绍
  • Python中列表、字典、元组、集合数据结构整理
  • python求列表交集的方法汇总
  • Python入门篇之列表和元组
  • python实现忽略大小写对字符串列表排序的方法
  • Python中列表(list)操作方法汇总
  • Python中无限元素列表的实现方法
  • Python常用列表数据结构小结
  • Python 列表(List)操作方法详解
  • Python列表计数及插入实例
Tags:python 列表推导

相关文章

  • 2015-05-05python3序列化与反序列化用法实例
  • 2015-02-02Python中非常实用的一些功能和函数分享
  • 2015-05-05python获取一组数据里最大值max函数用法实例
  • 2014-08-08Python深入学习之装饰器
  • 2015-06-06python获得文件创建时间和修改时间的方法
  • 2009-07-07python 解析html之BeautifulSoup
  • 2014-10-10跟老齐学Python之私有函数和专有方法
  • 2015-08-08Python中for循环和while循环的基本使用方法
  • 2016-01-01Python中http请求方法库汇总
  • 2014-09-09跟老齐学Python之做一个小游戏

最新评论

  </div><!--endborder-->  </div><!--end fl-->

大家感兴趣的内容

  • 1Python入门教程 超详细1小时学会
  • 2python 中文乱码问题深入分析
  • 3比较详细Python正则表达式操作指
  • 4python strip()函数 介绍
  • 5Python 列表(List)操作方法详解
  • 6Python字符串的encode与decode研
  • 7pycharm 使用心得(一)安装和首
  • 8python 字符串split的用法分享
  • 9Python 字典(Dictionary)操作详解
  • 10Python科学计算环境推荐——Anac

最近更新的内容

    • Python使用bs4获取58同城城市分类的方法
    • Python使用CMD模块更优雅的运行脚本
    • 教你如何在Django 1.6中正确使用 Signal
    • 六个窍门助你提高Python运行效率
    • python网络编程之读取网站根目录实例
    • python实现批量改文件名称的方法
    • 使用PyInstaller将Python程序文件转换为可
    • python去除文件中空格、Tab及回车的方法
    • Python3.0与2.X版本的区别实例分析
    • pycharm 使用心得(九)解决No Python in

常用在线小工具

  </div><!--end fr-->  </div>



0 0
原创粉丝点击