Python basics ONLINE problem sets data types

Posted by ktsirig on Sun, 05 Jan 2020 06:05:20 +0100

3.1 synthesize tuples (1,2,3) and sets {"four",5,6} into a list

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 set more than 5 elements to 0 and less than 5 elements to 1 in list [3,7,0,5,1,8]

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 convert the list ["mo","deng","ge"] and [1,2,3] to [("Mo", 1), (Deng, 2), (GE, 3)]

 1 #Method 1: ergodic element method
 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 #Method 2: ergodic subscript method
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 #Method 3: slice combination method
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 #Method 4: traversal subscript opportunism
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 #Operation result: 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 if a = dict(), make b = a, execute b.update({"x":1}),a also changes, why and how to avoid

Reason: a variable assigned to another variable is equivalent to the values stored in the same address referenced by the two variables

Solution: re opening the space can cancel the association between two variables (each expression will have a value, and the value referenced by the variable name depends on what is assigned to it)

 1 #Method 1: copy()Function replication
 2 a = {1:"mo",2:"deng"}
 3 b = a.copy()
 4 b.update({"x":"/"})
 5 print(a,b)
 6 
 7 #Method 2: unpacking assignment method
 8 a = {1:"mo",2:"deng"}
 9 b = dict()
10 b.update(a)
11 b.update({"x":"/"})
12 print(a,b)
13 
14 #Operation result:
15 """
16 {1: 'mo', 2: 'deng'} {1: 'mo', 2: 'deng', 'x': '/'}
17 {1: 'mo', 2: 'deng'} {1: 'mo', 2: 'deng', 'x': '/'}
18 """

3.5 convert the two-dimensional structure [['a',1],['b',2]] and (('x',3),('y',4)) into a dictionary

1 #Make a 2D structure[["a","/"],["b",2]]and(("x",3),("y",4))Convert to dictionary
2 list1,tuple1=[["a","/"],["b",2]],(("x",3),("y",4))
3 dict1=dict(list1)
4 dict2=dict(tuple1)
5 print(dict1,dict2)
6 #Operation result:
7 """
8 {'a': '/', 'b': 2} {'x': 3, 'y': 4}
9 """

3.6

3.7

 

 

Topics: Python less