#(1).{'x': 'A', 'y': 'B', 'z': 'C' } 把字典写成x=A,y=B,z=C的列表推导式 dic = {'x': 'A', 'y': 'B', 'z': 'C' } # for a,b in dic.items(): # print(a,b) res = [a+"="+b for a,b in dic.items() ] print(res) # (2).把列表中所有字符变成小写 ["ADDD","dddDD","DDaa","sss"] lst = ["ADDD","dddDD","DDaa","sss"] res = [i.lower() for i in lst ] print(res) # (3).x是0-5之间的偶数,y是0-5之间的奇数 把x,y组成一起变成元组,放到列表当中 # (0 2 4 ) # (1 3 5) # (0 1) (0 3) (0 5) # (2 1) (2 3) (2 5) # (4 1) (4 3) (4 5) lst_new = [] for i in range(0,6): if i % 2 == 0: for j in range(0,6): if j % 2 == 1: lst_new.append( (i,j) ) print(lst_new) # 写法一 res = [(i,j) for i in range(0,6) if i % 2 == 0 for j in range(0,6) if j % 2 == 1 ] print(res) lst_new2 = [] for i in range(0,6): for j in range(0,6): if i % 2==0 and j %2 ==1: lst_new2.append( (i,j) ) print(lst_new2) # 写法二 res = [(i,j) for i in range(0,6) for j in range(0,6) if i % 2 == 0 and j % 2 == 1 ] print(res) # (4).使用列表推导式 制作所有99乘法表中的运算 for i in range(1,10): for j in range(1,i+1): # print("%d*%d=%2d " % (i,j,i*j)) print("{:d} * {:d} = {:2d} ".format(i,j,i*j) ,end="") print() # 写法一 res = ["{:d} * {:d} = {:2d} ".format(i,j,i*j) for i in range(1,10) for j in range(1,i+1)] print(res) for i in range(9,0,-1): for j in range(1,i+1): # print("%d*%d=%2d " % (i,j,i*j)) print("{:d} * {:d} = {:2d} ".format(i,j,i*j) ,end="") print() # 写法二 res = ["{:d} * {:d} = {:2d} ".format(i,j,i*j) for i in range(9,0,-1) for j in range(1,i+1)] print(res) ''' (5)#求M,N中矩阵和元素的乘积 # M = [ [1,2,3], # [4,5,6], # [7,8,9] ] # N = [ [2,2,2], # [3,3,3], # [4,4,4] ] =>实现效果1 [2, 4, 6, 12, 15, 18, 28, 32, 36] =>实现效果2 [[2, 4, 6], [12, 15, 18], [28, 32, 36]] ''' M = [[1,2,3],[4,5,6],[7,8,9]] N = [[2,2,2],[3,3,3],[4,4,4]] # M[0][0] * N[0][0] = 2 # M[0][1] * N[0][1] = 4 # M[0][2] * N[0][2] = 6 # M[1][0] * N[1][0] = 12 # M[1][1] * N[1][1] = 15 # M[1][2] * N[1][2] = 18 # M[2][0] * N[2][0] = 28 # M[2][1] * N[2][1] = 32 # M[2][2] * N[2][2] = 36 # 效果1 # i=> 0 1 2 j=> 0 1 2 i动的慢 j动的块 res = [M[i][j] * N[i][j] for i in range(3) for j in range(3) ] print(res) #[2, 4, 6, 12, 15, 18, 28, 32, 36] #=>实现效果2 [ [2, 4, 6], [12, 15, 18], [28, 32, 36] ] # [] [] [] ''' 第一步遍历三个空列表 [ [] for i in range(3) ] 第二部在空列表里面在写一个推导式遍历对应的元素 [M[i][j] * N[i][j] for j in range(3)] ''' res = [ [M[i][j] * N[i][j] for j in range(3)] for i in range(3) ] print(res) #[[2,4,6], [], []]