Home > Backend Development > Python Tutorial > python中的列表推导浅析

python中的列表推导浅析

WBOY
Release: 2016-06-16 08:44:19
Original
1293 people have browsed it

列表推导(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 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]
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template