马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 中英文泡椒 于 2023-5-15 17:35 编辑
打卡笔记:
1.再谈列表推导式
这样创建的B不是一个二维列表,只是对同一个列表的三次引用
给其中一个元素赋值,影响的不单单一个元素B
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
创建二维列表A
>>> A = [0] * 3
>>> for i in range(3):
A[i] = [0] * 3
>>> A
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> A[1][1] = 1
>>> A
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
用列表推导式创建嵌套列表
>>> S = [[0] * 3 for i in range(3)]
>>> S
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> S[1][1] = 1
>>> S
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
2.列表推导式还可以添加一个用于筛选的if分句
[expression for target in iterable if condition]
>>> even = [i for i in range(10) if i % 2 == 0]
>>> even
[0, 2, 4, 6, 8]
检测先执行for语句,在执行if语句,最后执行左侧的表达式
>>> even = [i + 1 for i in range(10) if i % 2 == 0]
>>> even
[1, 3, 5, 7, 9]
从这五个单词中筛选出‘F’开头的单词
>>> words = ["Great", "FishC", "Brilliant", "Excellent", "Fantistic"]
>>> words = ["Great", "FishC", "Brilliant", "Excellent", "Fantastic"]
>>> fwords = [w for w in words if w[0] == 'F']
>>> fwords
['FishC', 'Fantastic']
3.列表推导式还可以变得更复杂一些,那就是实现嵌套
[expression for target1 in iterable1
for target2 in iterable2
...
for targetN in iterableN]
将二维列表降级为一维列表
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> flatten = [col for row in matrix for col in row]
>>> flatten
[1, 2, 3, 4, 5, 6, 7, 8, 9]
转换成循环的实现
>>> flatten = []
>>> for row in matrix:
for col in row:
flatten.append(col)
>>> flatten
[1, 2, 3, 4, 5, 6, 7, 8, 9]
笛卡尔乘积
>>> [x + y for x in "fishc" for y in "FISHC"]
['fF', 'fI', 'fS', 'fH', 'fC', 'iF', 'iI', 'iS', 'iH', 'iC', 'sF', 'sI', 'sS', 'sH', 'sC', 'hF', 'hI', 'hS', 'hH', 'hC', 'cF', 'cI', 'cS', 'cH', 'cC']
转换成循环
>>> _ = []
>>> for x in "fishc":
for y in "FISHC":
_.append(x + y)
>>> _
['fF', 'fI', 'fS', 'fH', 'fC', 'iF', 'iI', 'iS', 'iH', 'iC', 'sF', 'sI', 'sS', 'sH', 'sC', 'hF', 'hI', 'hS', 'hH', 'hC', 'cF', 'cI', 'cS', 'cH', 'cC']
[某个变量名是临时的或者无关紧要的,就可以直接用一个下划线当变量名]
4.列表推导式的终极用法
[expression for target1 in iterable1 if condition1
for target2 in iterable2 if condition2
...
for targetN in iterableN if conditionN]
举例
>>> [[x, y] for x in range(10) if x % 2 == 0 for y in range(10) if y % 3 == 0]
[[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 x in range(10):
if x % 2 == 0:
for y in range(10):
if y % 3 == 0:
_.append([x, y])
>>> _
[[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]]
程序设计原则“KISS”(全称:Keep It Simple & Stupid[/i])
|