Catalog
python day4 tuple/dictionary/set class knowledge point supplement
(Learning resources come from the education of older boys)
2019/10/7
1. tuple knowledge point supplement
- Create and transform
t = (11,22,33)
t = tuple(iterable), such as tuple([11,22,33])
-
Characteristics of tuples
Characteristics of tuples: Elements of tuples are not modifiable, but elements of elements can be modified. That is, the son of the tuple can not change, but the grandson of the tuple can change.
t = (11,22,33,['lan',{'name':'lanxing'}]) t[5]=44 #Errors are reported because elements of tuples are not modifiable t[3][0]='xing' #No error will be reported, because the grandson of the tuple can modify it.
2. Knowledge Point Supplement of Dictionary dict
- Create and transform
dict1 = {'k1':33,'k2':'xy'}
dict2=dict(k1=33,k2='xy') ` essentially the second method is used.
- The value fromkeys points to the same memory address
d1 ={'k1':[],'k2':[],'k3':[]} d1['k1'].append('x') print(d1) d2 =d1.fromkeys(d1,[]) x1 = d2['k1'].append('x') print(d2) # Because from keys (iterable, v), this V points to the same memory address.
3. Basic data type set
Set is an unordered and unique set of elements. Collections are mainly used for relational testing.
- Create a collection
s1 = {1,2,'x','y',True}
S2 = set ((1,2,'x','y', True)) The parameters in set () are iterative objects.
Collection set is essentially the keys of a dictionary.
- Method of Set
add,clear,difference,difference_update,discard,remove,intersection,isdisjoint,issubset,
s2 = set((1,2,'x','y',True)) s2.add(3) #Add element 3 to the collection s2.add('z') s1 = {1,2,'x','y',True,'name'} s1.difference(s2) # Look for elements that exist in s1 and do not exist in s2. Finding difference sets s1-s2 # Look for elements that exist in s1 and do not exist in s2. The same function as difference s1.difference_update(s2) # Find the elements that exist in s1 and do not exist in s2, and update yourself, that is, s1 removes the intersection between the two. s1.discard('x') #Remove the specified element, and the element does not exist and does not report an error. s1.discard('x') #Removal of the specified element will cause an error if it does not exist. s1.intersection(s2) #Look for intersection, that is, there are elements in s1 and s2. s1.isdisjoint(s2) #Judge whether there is no intersection, there is intersection is False, there is no intersection is False. s1.issubset(s2) # Judging whether s1 is s2 is a subset s1.symmetric_difference(s2) #To find the symmetric difference set, that is, there exists in s1 and s2, but it is not an element that exists in both sides. s1 ^ s2 # Finding Symmetric Difference Set s1.union(s2) #Seeking Union. s1 | s2 #Seeking Union
Homework:
There are two dictionaries, old_dict and new_dict, which require:
- If the keys of the two dictionaries are the same, the value in old_dict[key] is updated to the value of new_dict[key].
- new_dict.keys() exist, add in old, not exist, delete in old.
old_dict =dict(#1=11,#2=22,#3=100) new_dict = dict(#1=33,#4=22,#7=100) # If the key s of the dictionary are the same, we can judge whether there is intersection, so the first step is to find the intersection. s1 = set(old_dict.keys()) s2 = set(new_dict.keys()) s3 = s1.intersection(s2) # Use for iteration to update values in old for i in s3: old_dict[i] = new_dict[i] # Find the difference set between s1 and s2, and iterate to delete the old elements. s4 = s1 - s2 for i in s4: old_dict.pop(i) s5 = s2 - s1 for i in s5: old_dict[i]=new_dict[i] print(old_dict)
4. Ternary operations, also known as trinomial operations
if 1==1: name ='x' else: name='y' name ='x' if 1==1 else 'y' #This is called ternary operation.
5. Deep duplication and shallow duplication
- For numbers and strings, there is no need to investigate the difference between deep and shallow replication, because they are immutable objects that always point to the same memory address.
- For lists, dictionaries, tuples, collections, etc., depth replication is different.
In shallow replication, only the first layer memory address is replicated, while in deep replication, all the addresses are replicated.
import copy li1 = [1,2,[3,4]] li2 = copy.copy(li1) # Shallow copy, just copy the memory address reference of the first layer element. That is to say, the length of the nested list of li2 will affect the nested list of the original list. id(li1) == id(li2) li2[2].append(5) li2.append(6) print(li1,li2) li3 = copy.deepcopy(li1) # Deep copy, any modification of li3 has nothing to do with li1. li3[2].append(5) li3.append(6) print(li1,li3)
6. function
There are three types of programming: functional programming, object-oriented process, and process-oriented programming.
- PROCESS-ORIENTED PROGRAMMING: Functions are implemented in sequence from top to bottom according to business logic. The most common operation in the development process is paste copy, which is to copy the previous code blocks to the existing functions.
- Functional Programming: Functions are programmed from specified functions, which are taken out whenever you want to use them. In functional programming, every function is a function. Functional programming starts with verbs.
- Object-Oriented Programming: Classify different objects and consider what functions different objects have. Nouns, i.e. different objects, should be considered first in development.
- Defined function
Functions are blocks of code with functions that can be reused continuously.
Mathematical function: f(x,y)=xy2,f is the function name, x,y is the parameter, XY2 is the function execution statement.
- The grammar of defining functions:
def funcname(x,y,z='hello',*args,**kwargs): #Defined function print(x,y,z,args,kwargs) #Execution statement of function return x,y,z,args,kwargs #Return value of function
- def is the key to define a function, funcname is the name of a function, is a variable, can be constantly modified, () is the parameters of the function, the content behind the return keyword is the return value of the function. When you call a function, you end up with return. If there is no return keyword, it returns None (empty) by default.
If you call a function, funcname(1,2), or function name + parentheses (parameter 1, parameter 2), will automatically execute the body of the function (the execution statement of the function).
- Parameters of functions
def func(x,y,z='hello'): pass #pass keyword is nothing. It means placeholder.
- x,y,z in parentheses is called the position parameter in the parameter. When it is executed, func(1,2), which means that 1, 2 is assigned to x,y, or 1, 2 is passed into the parameter x,y. Here 1 and 2 are called arguments.
- z is called the default parameter. The default parameter is optionally passed in when the function is called. If not, the default parameter is'hello'.
-
When a function is called, the parameters are passed in by default according to the location of the parameters. The argument for the default parameter must follow the position parameter. But if the specified parameter is passed into the argument, it can be out of order
func(1,2),func(y=2,x=1) are the same effect, there is no parameter z passed in, because z has a default value.
func(1,2,4) has the same effect as func(y=2,z=4,x=1).
Function dynamic parameters: Dynamic parameters can receive infinite arguments.
def myfunc(x,y,z='hello',*args,**kwargs): # Where * args is called dynamic location parameter and ** kwargs is called dynamic keyword parameter print(x,y,z,args,kwargs,sep=',') #Execution statement of function return x,y,z,args,kwargs #Return value of function
When a function is called, the dynamic location parameter must precede the dynamic keyword parameter. Dynamic location parameter is a tuple, and dynamic keyword parameter is a dictionary.
myfunc(1, 2, 'hellow world', 4, 5, k='hello,lanxing', my='lanxing')
1,2,hellow world,(4, 5),{'k': 'hello,lanxing', 'my': 'lanxing'}
- When dynamic parameters are passed into lists, dictionaries and tuples, lists indicate that every element in the list is passed in as an argument of position parameters. A dictionary is a dictionary that treats every key-value pair in the dictionary as a keyword parameter.
- Global and local variables
Variables in a function only act inside the function and have no effect on the outside world.
a=1 #Global functions, all work. def func1(): b=2 #local variable global a #Declaring a as a global variable through the keyword global affects a outside the function a = 3 #Modified the assignment of global variable a print(a) #Global variables act on the entire page print(b) print(a) #The output here is the modified global variable a. print(b) #Errors are reported because local variables only act inside the function. func1() #Calling function
def countLength(s): li1 = [] li2 = [] li3 = [] for i in range(len(s)): if s[i].isdigit(): li1.append(s[i]) elif s[i].isalpha(): li2.append(s[i]) elif s[i].isspace(): li3.append(s[i]) return len(li1), len(li2), len(li3), len(s)-len(li1)-len(li2)-len(li3) #CountLength ('123 XYZ AA * * * *') def countLen(obj): if len(obj) >= 5: print('%s Length greater than 5' % obj) else: print('%s Length less than 5' % obj) # countLen([1, 2, 3, 4]) def isSpace(obj): a = 0 for i in obj: for j in i: if j.isspace(): a += 1 return a li = ['x y', 'abc12 4 5', ' z y '] # print(isSpace(li)) def chlist(li): if len(li) > 2: return li[:2] return li #print(chlist([1, 2, 3, 4])) def oddSeq(li): list1 = [] for i in range(len(li)): if i % 2 != 0: list1.append(li[i]) return list1 #print(oddSeq([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) dict1 = {'k1': 'v1v1', 'k2': [11, 22, 33, 44]} def lenDict(**kwargs): for k, v in kwargs.items(): if len(v) > 2: kwargs[k] = v[:2] return kwargs # print(lenDict(**dict1)) def feibonaqi(n): if n == 0: return 0 elif n==1: return 1 else: return feibonaqi(n-2)+feibonaqi(n-1) #Recursion refers to calling oneself inside a function, which is equivalent to f (x) = f (x-1) and f (0) = 0 in a mathematical function. print(feibonaqi(9)) i = 0 li =[] while i<10: li.append(feibonaqi(i)) i +=1 print(li,len(li))