《零基础入门学习Python》打卡笔记(二十)
本帖最后由 中英文泡椒 于 2023-5-15 17:35 编辑https://www.bilibili.com/video/BV1c4411e77t?p=26&vd_source=451f1e8f04d8c94807752b187ccd4c7e
打卡笔记:
1.再谈列表推导式
B = [ * 3] * 3
这样创建的B不是一个二维列表,只是对同一个列表的三次引用
B = 1
给其中一个元素赋值,影响的不单单一个元素
B
[, , ]
创建二维列表A
>>> A = * 3
>>> for i in range(3):
A = * 3
>>> A
[, , ]
>>> A = 1
>>> A
[, , ]
用列表推导式创建嵌套列表
>>> S = [ * 3 for i in range(3)]
>>> S
[, , ]
>>> S = 1
>>> S
[, , ]
2.列表推导式还可以添加一个用于筛选的if分句
>>> even =
>>> even
检测先执行for语句,在执行if语句,最后执行左侧的表达式
>>> even =
>>> even
从这五个单词中筛选出‘F’开头的单词
>>> words = ["Great", "FishC", "Brilliant", "Excellent", "Fantistic"]
>>> words = ["Great", "FishC", "Brilliant", "Excellent", "Fantastic"]
>>> fwords = == 'F']
>>> fwords
['FishC', 'Fantastic']
3.列表推导式还可以变得更复杂一些,那就是实现嵌套
[expression for target1 in iterable1
for target2 in iterable2
...
for targetN in iterableN]
将二维列表降级为一维列表
>>> matrix = [, , ]
>>> flatten =
>>> flatten
转换成循环的实现
>>> flatten = []
>>> for row in matrix:
for col in row:
flatten.append(col)
>>> flatten
笛卡尔乘积
>>>
['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]
举例
>>> [ for x in range(10) if x % 2 == 0 for y in range(10) if y % 3 == 0]
[, , , , , , , , , , , , , , , , , , , ]
转换成循环
>>> _ = []
>>> for x in range(10):
if x % 2 == 0:
for y in range(10):
if y % 3 == 0:
_.append()
>>> _
[, , , , , , , , , , , , , , , , , , , ]
程序设计原则“KISS”(全称:Keep It Simple & Stupid)
《KISS) 歌者文明清理员 发表于 2023-5-15 17:53
《KISS)
{:10_281:}是这样吗 中英文泡椒 发表于 2023-5-15 17:54
是这样吗
https://t3.wodetu.cn/2023/05/15/2cf4bde4c074ab4cc57e9c1555315e6a.png 怎么加载的视频连接?
页:
[1]