# 详解Python列表推导式

[表达式 for 变量 in 序列或迭代对象 if 条件表达式]

>>> aList = [x*x for x in range(10)]

>>> aList = []

>>> for x in range(10):

aList.append(x*x)

>>> sum([2**i for i in range(64)])

18446744073709551615

（1）实现嵌套列表的平铺

>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> [num for elem in vec for num in elem]

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

>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> result = []

>>> for elem in vec:

for num in elem:

result.append(num)

>>> result

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

（2）过滤不符合条件的元素

>>> import os

>>> [filename for filename in os.listdir('.') if filename.endswith('.py')]

>>> aList = [-1, -4, 6, 7.5, -2.3, 9, -11]

>>> [i for i in aList if i>0] #所有大于0的数字

[6, 7.5, 9]

>>> scores = {"Zhang San": 45,

"Li Si": 78,

"Wang Wu": 40,

"Zhou Liu": 96,

"Zhao Qi": 65,

"Sun Ba": 90,

"Zheng Jiu": 78,

"Wu Shi": 99,

"Dong Shiyi": 60}

>>> highest = max(scores.values()) #最高分

>>> lowest = min(scores.values()) #最低分

>>> average = sum(scores.values())/len(scores) #平均分

>>> highest, lowest, average

(99, 40, 72.33333333333333)

>>> highestPerson = [name for name, score in scores.items() if score == highest]

>>> highestPerson

['Wu Shi']

（3）同时遍历多个列表或可迭代对象

>>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

>>> result = []

>>> for x in [1, 2, 3]:

for y in [3, 1, 4]:

if x != y:

result.append((x,y))

>>> result

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

（4）使用列表推导式实现矩阵转置

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

>>> [[row[i] for row in matrix] for i in range(4)]

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

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

>>> result = []

>>> for i in range(len(matrix[0])):

result.append([row[i] for row in matrix])

>>> result

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

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

>>> result = []

>>> for i in range(len(matrix[0])):

temp = []

for row in matrix:

temp.append(row[i])

result.append(temp)

>>> result

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

（5）列表推导式中可以使用函数或复杂表达式

>>> def f(v):

if v%2 == 0:

v = v**2

else:

v = v+1

return v

>>> print([f(v) for v in [2, 3, 4, -1] if v>0])

[4, 4, 16]

（6）列表推导式支持文件对象迭代

>>> with open('C:\\RHDSetup.log', 'r') as fp:

print([line for line in fp])

（7）使用列表推导式生成100以内的所有素数

>>> from math import sqrt

>>> [ p for p in range(2, 100) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

656 篇文章93 人订阅

0 条评论

## 相关文章

11110

13310

### 多益网络2016春季实习校招笔试回顾（C++游戏后台开发）

2016.04.16晚中山大学大学城校区（东校区）参加了多益网络的C++游戏后台开发的笔试。有几道笔试题还是值得斟酌和记录的，特记录如下。比较可惜，因为回老家了...

11820

### 递归与动态规划----基础篇2

ps:最近几天正在刷一些有关动态规划的题，我会把自己学习时的想法以及做题的想法记录下来。如果你觉得对你有帮助，欢迎关注，谢谢。

10920

36590

80570

12820

### Numpy教程第1部分 - 阵列简介（常用基础操作总结）

【导读】这里是numpy教程的基础部分，涵盖了使用numpy的ndarrays执行数据操作和分析的一些操作。众所周知，Numpy是Python中最基本和最强大的...

29840

### 入门 | 数据科学初学者必知的NumPy基础知识

NumPy（Numerical Python）是 Python 中的一个线性代数库。对每一个数据科学或机器学习 Python 包而言，这都是一个非常重要的库，S...

15020

25590