列表推导式举例:Python打印99乘法表
print('\n'.join([''.join(['%s*%s=%-2s '%(y,x,x*y)for y in range(1,x+1)])for x in range(1,10)]))
print('\n'.join([' '.join([f"{j}x{i}={i*j}" for j in range(1, i + 1)]) for i in range(1, 10)]))
列表推导式书写形式:
[表达式 for 变量 in 列表]
[表达式 for 变量 in 列表 if 条件]
# 计算0~9所有偶数平方
squares = []
for x in range(10):
if x%2 == 0:
squares.append(x**2)
squares
[0, 4, 16, 36, 64]
squares = [x**2 for x in range(10) if x%2==0]
squares
[0, 4, 16, 36, 64]
# 注意,这里的x和y没有关系
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
print([name for lst in names for name in lst if name.count('e') >= 2]) # 注意遍历顺序,这是实现的关键
[(str(x), x**2) for x in range(6)]
[('0', 0), ('1', 1), ('2', 4), ('3', 9), ('4', 16), ('5', 25)]
# 注意,这里的x和y是有关系的
vec = [[1,2,3], [4,5,6], [7,8,9]]
[y for x in vec for y in x]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
result = ["偶" if i % 2 == 0 else "奇" for i in range(1, 10+1) ]
print(result)
输出结果:[‘奇’, ‘偶’, ‘奇’, ‘偶’, ‘奇’, ‘偶’, ‘奇’, ‘偶’, ‘奇’, ‘偶’]
将中括号换成大括号,就变成了集合set推导式
# 返回的是去重元素的集合
a = {x for x in 'abracadabra' if x not in 'abc'}
a
{'d', 'r'}
将中括号换成大括号,并且返回元素是Key:Value形式,就变成了字典dict推导式
# 返回的是一个新的字典
{str(x): x**2 for x in (2, 4, 6)}
{'2': 4, '4': 16, '6': 36}
将一个字典的key和value对调
mcase = {'a': 10, 'b': 34}
mcase_frequency = {mcase[k]: k for k in mcase}
print(mcase_frequency)