1. 列表生成式
未使用生成式
alist = []
for i in range(1,11):
if (i % 2 == 0):
alist.append(i)
print(alist)
# 输出结果
[2, 4, 6, 8, 10]
使用生成式
alist = [i for i in range(1,11) if( i%2==0 )]
print(alist)
# 输出结果
[2, 4, 6, 8, 10]
2. 字典生成式
未使用生成式
adict={}
for i in range(1,11):
adict[i] = f'This is {i}'
print(adict)
# 输出结果
{1: 'This is 1', 2: 'This is 2', 3: 'This is 3', 4: 'This is 4', 5: 'This is 5', 6: 'This is 6', 7: 'This is 7', 8: 'This is 8', 9: 'This is 9', 10: 'This is 10'}
使用生成式
adict={i:f'This is {i}' for i in range(1,11)}
print(adict)
# 输出结果
{1: 'This is 1', 2: 'This is 2', 3: 'This is 3', 4: 'This is 4', 5: 'This is 5', 6: 'This is 6', 7: 'This is 7', 8: 'This is 8', 9: 'This is 9', 10: 'This is 10'}