<每日一題>題目12:列表解析及zip、dict函式的簡單應用
阿新 • • 發佈:2019-01-07
''' 分析: 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]] '''
執行結果: