# 3.推导式 通过推导式,可以快捷方便的根据一个已有的 可迭代对象,生成一个新的对象
lst = list(range(1, 11)) # new_lst = filter(lambda x: x % 2 == 0, lst) # print(list(new_lst)) # [2, 4, 6, 8, 10] # new_lst = map(lambda x: x * 2, lst) # print(list(new_lst)) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# 列表推导式 表达式: [expression for item in iterable if condition] –> 生成新列表
# [新列表中的元素 for 变量 in 原列表 if condition]
# 实现 map new_list = [x * 2 for x in lst] # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # 实现 filter new_list = [x * 2 for x in lst if x % 2 == 0] # [4, 8, 12, 16, 20] print(new_list)
# 生成一副扑克牌
shape_lst = ['♣️', '♥️', '♠️', '♦️'] num_lst = ['A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] pk_list = [s+n for s in shape_lst for n in num_lst]
# 生成器推导式:返回一个生成器而不是列表,好处:可以节省内存; (expression for item in iterable if condition)
pk_list = (s+n for s in shape_lst for n in num_lst) # pk_list = ({s: n} for s in shape_lst for n in num_lst) print(pk_list) # <generator object <genexpr> at 0x100cbaba0> print(next(pk_list)) # ♣️A print(next(pk_list)) # ♣️1
# 集合推导式:最外层是花括号包裹:好处:元素不重复;{expression for item in iterable if condition}
# 字典推导式:{key_expression: value_expression for expression in iterable if condition}
d = {k: 'g' for k in shape_lst} # 通过 列表推导字典 {'♣️': 'g', '♥️': 'g', '♠️': 'g', '♦️': 'g'} t_d = dict(a=1, b=2, c=3, d=4) # d = {k + "g": v for k, v in t_d.items()} # 通过 字典推导字典 {'ag': 1, 'bg': 2, 'cg': 3, 'dg': 4} print(d)
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/280129.html