Python基础_ONLINE习题集_03 数据类型
程序员文章站
2022-04-18 21:09:02
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