理解python中的列表推导


#Python


2014-03-04 19:20

列表推导(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]


( 本文完 )