<每日一题>题目12:列表解析及zip、dict函数的简单应用

it2022-05-05  133

''' 分析: 1.列表解析:迭代机制的一种应用 语法:   [expression for iter_val in iterable]    [expression for iter_val in iterable if cond_expr] 2.zip函数:以可迭代的对象作为参数,将对应元素打包成一个元组,形如:zip([a,b],[c,d])→[(a,c),(b,d)] dict函数:可以以可迭代方式创建字典,形如:dict([(a,b),(c,d)])→{a:b,c:d} ''' A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) A1 = range(10) A2 = [i for i in A1 if i in A0] A3 = [A0[s] for s in A0] A4 = [i for i in A1 if i in A3] A5 = {i:i*i for i in A1} A6 = [[i,i*i] for i in A1] ''' 解答: A0→A0=dict([("a",1),("b",2),("c",3),("d",4),("e",5])→A0={"a":1,"b":2,"c":3,"d":4,"e":5} A1→A1=[0,1,2,3,4,5,6,7,8,9] A2→ A2 = [] for i in A1: if i in A0: #字典进行in判断的时候判断的是key A2.append(i) →A2=[] A3→ A3 = [] for s in A0: A3.append(A0[s]) →A3=[1, 2, 3, 4, 5] A4→ A4=[] for i in A1: if i in A3: A4.append(i)→A4=[1, 2, 3, 4, 5] A5→ A5 = {} for i in A1: A5.update({i:i*i})→A5={0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} A6→ A6 = [] for i in A1: A6.append([i,i*i])→A6=[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]] '''

  运行结果:

转载于:https://www.cnblogs.com/shuimohei/p/10232668.html


最新回复(0)