解析式是将一个序列(实际上适用于任何可迭代对象(iterable))转换成另一个序列的工具。
一、将for循环改写成列表解析式:
numbers = [1, 2, 3, 4, 5]
# 一个没有条件语句的for循环
doubled_odds = []
for n in numbers:
doubled_odds.append(n * 2)
# 改写成一个列表解析式后:
doubled_odds = [n * 2 for n in numbers ]
# 一个有条件语句的for循环
doubled_odds = []
for n in numbers:
if n%2==0:
doubled_odds.append(n * 2)
# 改写成一个列表解析式后:
doubled_odds = [n * 2 for n in numbers if n%2==0 ]
二、将嵌套for循环改写成列表解析式:
# 一个嵌套循环
flattened = []
for row in matrix:
for n in row:
flattened.append(n)
# 改写成列表解析式后
flattened = [n for row in matrix for n in row]
三、集合解析式改写:
# 一个for循环遍历集合
first_letters = set()
for w in words:
first_letters.add(w[0])
# 改写成集合解析式
first_letters = {w[0] for w in words}
四、字典解析式改写:
# 一个字典for循环
flipped = {}
for key, value in original.items():
flipped[value] = key
# 改写成字典解析式
flipped = {value: key for key, value in original.items()}