python中的列表推导浅析

yipeiwu_com6年前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中用PIL库批量给图片加上序号的教程

Python中用PIL库批量给图片加上序号的教程

女友让我给她论文的图片上加上字母序号,本来觉得是个很简单的事情,但那个白底黑字的圆圈序号却难住了我, 试了几个常用的软件,都不行。 后来用 PS + 动作,倒是能搞出来,不过也不容易,正...

Python 脚本实现淘宝准点秒杀功能

Python 脚本实现淘宝准点秒杀功能

准备软件 下载地址 : https://download.csdn.net/download/tangcv/11968538 pycharm文件太大,不好上传 ,直接去官网下载:ht...

Python中字符串与编码示例代码

在最新的Python 3版本中,字符串是以Unicode编码的,即Python的字符串支持多语言 编码和解码    字符串在内存中以Unicode表示,在操作字符串时,经常需要...

使用python绘制二维图形示例

我就废话不多说了,直接上代码吧! import matplotlib.pyplot as plt #也可以使用 import pylab as pl import matplotli...

Python 连接字符串(join %)

join 方法用于连接字符串数组 s = ['a', 'b', 'c', ...