马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Nicole37 于 2023-9-17 17:13 编辑
列表推导式:
1、回顾:创建二维列表:a = [0]*3
for i in range(3):
a[i]=[0]*3
a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]
用嵌套列表得到该列表:a=[[0]*3 for i in range(3)]
a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
2、有if分句的列表推导式:[expression for target in iterable if condition]
e.g#取出09之间的偶数
even = [i for i in range(10) if i % 2 ==0]
even
[0, 2, 4, 6, 8]
注意:该结构先执行 for语句,在执行if语句,最后执行左面输出表达式
e.g#输出其中首字母为w的单词
words = ["what","do","you","want","to","eat","tomorrow"]
w = [words[i] for i in range(len(words)) if words[i][0]=="w"]
w
['what', 'want']
#法2:别忘记列表本身可以直接被循环遍历
w = [i for i in words if i[0]=='w']
w
['what', 'want']
3、列表推导式的嵌套:
[expression for i in b
for i in c
..........
for i in d]
e.g#二维列表展开为一维:
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [i for j in a for i in j]
b
[1, 2, 3, 4, 5, 6, 7, 8, 9]
#先写外层循环 for j in a,在写内层嵌套循环for i in j
#相当于下式
b=[]
for j in a:
for i in j:
b.append(i)
e.g#对应项乘积
[i+j for i in "honey" for j in "HONEY"]
['hH', 'hO', 'hN', 'hE', 'hY', 'oH', 'oO', 'oN', 'oE', 'oY', 'nH', 'nO', 'nN', 'nE', 'nY', 'eH', 'eO', 'eN', 'eE', 'eY', 'yH', 'yO', 'yN', 'yE', 'yY']
3、终极列表推导式:
[expression for i in b if h
for i in c if v
..........
for i in d if u]
e.g
注意:注意复杂的列表推导式是层层嵌套的,从左到右一级比一级高#输出(0-9)之间的组合,使得前者能被2整除,后者能被3整除
a=[[i,j] for i in range(10) if i%2==0 for j in range(10) if j%3==0]
a
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]
#_ 可以用于作为临时变量出现,等价于
_=[]
for i in range(10):
if i%2==0:
for j in range(10):
if j%3==0:
_.append([i,j])
_
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]
keep it simple & stupid~
作业:
1、请使用列表推导式创建一个 4 * 5 的二维列表,并将每个元素初始化为数字 8>>> s = [[8] * 5 for i in range(4)]
>>> s
[[8, 8, 8, 8, 8], [8, 8, 8, 8, 8], [8, 8, 8, 8, 8], [8, 8, 8, 8, 8]]
4 * 5 就是 4 行 5 列,那么就是内层嵌套列表包含 5 个元素,外层列表包含 4 个嵌套列表的意思啦
2、请将下面 matrix 矩阵反向展开,即使得最终的结果为 [9, 8, 7, 6, 5, 4, 3, 2, 1]>>> matrix = [[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
>>> flatten = [col for row in matrix for col in row][::-1]
>>> flatten
[9, 8, 7, 6, 5, 4, 3, 2, 1]
先按顺序取出来,在用切片,从头到尾,-1表示倒着取
3、请使用列表推导式,获得 matrix 矩阵的转置矩阵 Tmatrixmatrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
#循环版本
x=[0]*4
for a in range(4):
x[a]=[0]*3
for i in range(3):
for j in range(4):
x[j][i]=matrix[i][j]
自己的答案,转置就是ij 变ji
注意:如果是反过来的就是-1 ,从9到2,以-1为间隔
|