3.1 將元組(1,2,3) 和集合{"four",5,6}合成一個列表 1 tuple,set,list = (1,2,3),{"four",5,6},[] 2 for i in tuple: 3 list.append(i) 4 for j in set: 5 list.append(j) 6 ...
3.1 將元組(1,2,3) 和集合{"four",5,6}合成一個列表
1 tuple,set,list = (1,2,3),{"four",5,6},[] 2 for i in tuple: 3 list.append(i) 4 for j in set: 5 list.append(j) 6 print(list)
3.2 將列表[3,7,0,5,1,8]中大於5元素置為0,小於5的元素置為1
1 list2 = [3,7,0,5,1,8] 2 print(list2) 3 for i in range(0,len(list2)): 4 if list2[i] >5: 5 list2[i] = 0 6 elif list2[i]<5: 7 list2[i]=1 8 print(list2)
3.3 將列表["mo","deng","ge"]和[1,2,3] 轉換成[("mo",1),("deng",2),("ge",3)]
1 #方法一:遍歷元素法 2 Sl1,Nl1,new_list1=["mo","deng","ge"],[1,2,3],[] 3 for i in Sl1: 4 for j in Nl1: 5 if Sl1.index(i) == Nl1.index(j): 6 new_list1.append((i,j)) 7 print("new_list1=",new_list1) 8 9 #方法二:遍歷下標法 10 Sl2,Nl2,new_list2=["mo","deng","ge"],[1,2,3],[] 11 for a in range(0,len(Sl2)): 12 for b in range(0,len(Nl2)): 13 if a == b: 14 new_list2.append((Sl2[a],Nl2[b])) 15 print("new_list2=",new_list2) 16 17 #方法三:切片組合法 18 Sl3,Nl3=["mo","deng","ge"],[1,2,3] 19 print("new_list3=",[(Sl3[0],Nl3[0]),(Sl3[1],Nl3[1]),(Sl3[2],Nl3[2])]) 20 21 #方法四:遍歷下標投機取巧法 22 Sl4,Nl4,new_list4=["mo","deng","ge"],[1,2,3],[] 23 for k in range(0,3): 24 new_list4 += [(Sl4[k],Nl4[k])] 25 print("new_list4=",new_list4)
26 #運行結果: 27 """ 28 new_list1= [('mo', 1), ('deng', 2), ('ge', 3)] 29 new_list2= [('mo', 1), ('deng', 2), ('ge', 3)] 30 new_list3= [('mo', 1), ('deng', 2), ('ge', 3)] 31 new_list4= [('mo', 1), ('deng', 2), ('ge', 3)] 32 """
3.4 若a = dict(),令 b = a,執行b.update({"x":1}),a亦改變,為何,如何避免
原因:一個變數賦給另一個變數等價於這兩個變數引用同一個地址所存儲的值
解決:重新開闢空間可以取消兩變數間的關聯(每一個表達式都會有值都會重新開闢空間,變數名所引用的值要看賦給它的是什麼)
1 #方法一:copy()函數複製 2 a = {1:"mo",2:"deng"} 3 b = a.copy() 4 b.update({"x":"/"}) 5 print(a,b) 6 7 #方法二:解包賦值法 8 a = {1:"mo",2:"deng"} 9 b = dict() 10 b.update(a) 11 b.update({"x":"/"}) 12 print(a,b) 13 14 #運行結果: 15 """ 16 {1: 'mo', 2: 'deng'} {1: 'mo', 2: 'deng', 'x': '/'} 17 {1: 'mo', 2: 'deng'} {1: 'mo', 2: 'deng', 'x': '/'} 18 """
3.5 將二維結構[['a',1],['b',2]]和(('x',3),('y',4))轉換成字典
1 #將二維結構[["a","/"],["b",2]]和(("x",3),("y",4))轉換成字典 2 list1,tuple1=[["a","/"],["b",2]],(("x",3),("y",4)) 3 dict1=dict(list1) 4 dict2=dict(tuple1) 5 print(dict1,dict2) 6 #運行結果: 7 """ 8 {'a': '/', 'b': 2} {'x': 3, 'y': 4} 9 """
3.6
3.7