生成器
# 列表生成式(列表推导式):列表生成式性能高于列表操作
print([item for item in range(21) if item % 2 == 1])
print([item ** 2 for item in range(21) if item % 2 == 1])
生成式
# 生成器表达式
ood_gen = (item for item in range(21) if item % 2 == 1)
print(type(ood_gen))
odd_list = list(ood_gen)
print(type(odd_list), odd_list)
字典推导式
# 字典推导式
my_dict = {'tom': 22, 'immoc': 50, 'bobby': 90}
print({value: key for key, value in my_dict.items()})
my_list = [('tom', 22), ('immoc', 50), ('bobby', 90)]
print({value: key for key, value in my_list})
集合推导式
# 集合推导式
my_set = {key for key in my_dict.keys()}
print(type(my_set),my_set)
共有 0 条评论