|
发表于 2021-5-19 11:00:25
|
显示全部楼层
**1.再谈列表推导式**
B不是一个二维列表,只是对同一个列表的三次引用
>>> B = [[0] * 3] * 3
>>> B
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> B[1][1] = 1
>>> 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]]
列表推导式还可以添加一个用于筛选的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']
列表推导式还可以变得更复杂一些,那就是实现嵌套
[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']
[某个变量名是临时的或者无关紧要的,就可以直接用一个下划线当变量名]
列表推导式的终极用法
[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)
|
|