# [reprint] Python - list comprehension

reprintpythonlistcomprehension

# Python 列表推导式

## 一.Why learn list comprehensions 母鸡啊

1. List comprehensions can be said in PythonIt is widely used in program development.
2. List comprehensions can be used in a very concise way to quickly generate lists that satisfy specific needs,And the code is very readable.
3. Python的内部实现对列表推导式做了大量优化,Can guarantee fast running speed.

## 二.Start learning about list comprehensions 快醒醒

### 语法

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

### 具体操作：

#### ① 简单举例

``````>>> list = [x*x for x in range(10)]
>>> print(list)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> print(sum(list))
285

#### ② 使用列表推导式实现嵌套列表的平铺

``````>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> list = [num for elem in vec for num in elem]
>>> print(list)
[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)
print(result)

#### ③ 过滤不符合条件的元素

``````>>> list = [1,2,3,45,6,7,7,8,90,22]
>>> list = [i for i in list if i >10] #if条件判断
>>> list
[45, 90, 22]
>>> list = [x*x if x%2 != 0 else x for x in[1,2,3,4,5]] #if-else条件判断
>>> list
[1, 2, 9, 4, 25]
#List of known grades to find the highest scoring students
scores = {'zhangsan':11,"lisi":22,"wanngwu":33}
highest = max(scores.values())
highestperson = [name for name,score in scores.items() if score == highest]
print(highestperson)
#Use a list comprehension to find the position of the largest element in a list
>>> from random import randint
>>> x = [randint(1,10) for i in range(10)]#randint（1,10）是在1-10之间随机生成一个数,后面range（10）The role is to cycle10次
>>> x
[2, 6, 5, 9, 7, 4, 8, 3, 1, 5]
>>> m = max(x)
>>> m
9
>>> index_l = [index for index,value in enumerate(x) if value == m]
>>> index_l
[3]

#### ④ 使用多个循环实现多序列元素的任意组合

``````>>> l = [(x,y) for x in[1,2,3] for y in[3,2,4] if x != y]
>>> l
[(1, 3), (1, 2), (1, 4), (2, 3), (2, 4), (3, 2), (3, 4)]
''' 对于包含多个循环的列表推导式,Be sure to understand the execution order or nesting relationship of multiple loops '''

#### ⑤ 使用列表推导式实现矩阵转置

``````>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> re_matrix = [[row[i] for row in matrix]for i in range(3)]
>>> re_matrix
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

#### ⑥ 列表推导式中可以使用函数或复杂表达式

``````def f(v):
if v%2 == 0:
v *= 2
else:
v += 1
return v
print([f(v) for v in [-1,0,1,2,3] if v > 0])
print([v*2 if v%2==0 else v+1 for v in [-1,0,1,2,3] if v > 0])

#### ⑦ 列表推导式支持文件对象迭代

``````>>> fp = open("D:\各种文件\课程设计\Zhengzhou's 14th Five-Year Plan.txt",'r',encoding = 'utf-8')
>>> print([line for line in fp])
>>> fp.close()

## 三. Ask a simple question to practice

### 应用1：使用列表推导式生成 100 以内的所有素数

``````>>> import math
>>> l = [p for p in range(2,100) if 0 not in[p%d for d in range(2, int(math.sqrt(p))+1)]]
>>> l
[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]

I'm not cheating,The core code is indeed one line（傲娇 ）

### 应用2：实现矩阵转置

``````matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
print("原矩阵：",matrix)
print("转置矩阵为:",[[row[i] for row in matrix] for i in range(4)])