# ### 推导式 ''' 通过一行循环判断,遍历出一系列数据的方式就是推导式 特点:方便,简介,可以实现一些简单的功能 推导式当中只能跟循环和判断(单项分支) 种类中分为三种: 列表推导式,集合推导式,字典推导式 [val for val in iterable] {val for val in iterable} {a:b for a,b in iterable} ''' # (1)基本语法 # [1,2,3,4] => [2,4,6,8] lst = [1,2,3,4] lst2 = [] for i in lst: res = i * 2 lst2.append(res) print(lst2) res = [i for i in range(1,5)] # 改写 res = [i * 2 for i in range(1,5)] print(res) # [1,2,3,4] => [2,8,24,64] ''' 1-> 2 乘以2的1次幂 2-> 8 乘以2的2次幂 3 -> 24 乘以2的3次幂 4 -> 64 乘以2的4次幂 ''' # 把想要的值 写在for的左侧 res = [i << i for i in range(1,5)] # 1 << 1 2 << 2 3 << 3 4<<4 print(res) # (2)带有条件判断的推导式 lst = [1,2,3,4,5,6,67,7,8,98,9] lst2 = [] for i in lst: if i % 2 == 0: lst2.append(i) print(lst2) # 推导式写法 res = [i for i in lst if i %2 == 0] print(res) # (3)多循环推导式 lst1 = ["邓远文","舒畅","易思","仿真枪"] lst2 = ["张国成","王博","邱玉龙","苏传红"] lst = [] for i in lst1: for j in lst2: res = i + '♥♥♥' +j lst.append(res) print(lst) # "谁 ♥♥♥ 谁" res = [i+'♥♥♥'+j for i in lst1 for j in lst2 ] print(res) # (4)带有判断条件的多循环推导式 lst1 = ["邓远文","舒畅","易思","仿真枪"] lst2 = ["张国成","王博","邱玉龙","苏传红"] lst_new = [] for i in lst1: for j in lst2: if lst1.index(i) == lst2.index(j): strvar = i+'♥♥♥'+j lst_new.append(strvar) print(lst_new) res = [i+'♥♥♥'+j for i in lst1 for j in lst2 if lst1.index(i) == lst2.index(j)] print(res)