Python编程:列表、集合、字典推导式的示例

推导式,其实就是将多行的循环语句放到一行写

# -*- coding: utf-8 -*-
# 列表推导式
lst = [i for i in range(5)]
print(lst)
# [0, 1, 2, 3, 4]
# 相当于
lst2 = list()
for i in range(5):
lst2.append(i)
print(lst2)
# [0, 1, 2, 3, 4]
# 集合推导式
lst = [1, 2, 3, 3, 2, 4, 4]
st = {i for i in lst if i % 2 == 0}
print(st)
# {2, 4}
# 字典推导式
dct = {k: v for k, v in enumerate(range(5))}
print(dct)
# {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}