Article Directory
1. copy
1.1 Shallow copy of dictionary with copy()
Let's first look at the situation where two dictionaries point to the same object, it is not the case of copying.
d={'a':1,'b':2,'c':3}
d2=d
d2['a']=10
print('d=',d)
print('d2=',d2)
result
We found that the value of d2 has changed, and the value of d has also changed. This
is not the case if you use copy() to make a shallow copy of d. Changing one value will not affect the other.
d={'a':1,'b':2,'c':3}
d2=d.copy()
print('d2=',d2)
d2['a']=10
print('d=',d)
print('d2=',d2)
It can be seen that the value of d2 has changed, and the value of D has not been affected. In fact, after copying, another object was created.
d={'a':1,'b':2,'c':3}
d2=d.copy()
print('d id=',id(d))
print('d2 id=',id(d2))
1.2 Shallow copy is the copy sequence itself
Shallow copy is to copy the sequence itself, if there is a sequence in the sequence, it will not be copied, for example
d={'a':{'name':'葫芦娃','age':10,'sex':'男'},'b':2,'c':3}
d2=d.copy()
print('d=',d)
print('d2=',d2)
print('d id=',id(d))
print('d2 id=',id(d2))
d2['a']['name']='猪八戒'
print('d=',d)
print('d2=',d2)
print('d id=',id(d))
print('d2 id=',id(d2))
result
D:\Python38\python.exe D:/work/基础/Day09/课堂代码.py
d= {'a': {'name': '葫芦娃', 'age': 10, 'sex': '男'}, 'b': 2, 'c': 3}
d2= {'a': {'name': '葫芦娃', 'age': 10, 'sex': '男'}, 'b': 2, 'c': 3}
d id= 1838723700928
d2 id= 1838723701184
d= {'a': {'name': '猪八戒', 'age': 10, 'sex': '男'}, 'b': 2, 'c': 3}
d2= {'a': {'name': '猪八戒', 'age': 10, 'sex': '男'}, 'b': 2, 'c': 3}
d id= 1838723700928
d2 id= 1838723701184
Process finished with exit code 0
It can be seen that although the dictionary d2 successfully copied the dictionary d, when I modified the'name':'Calabash Baby' in the dictionary d2, the dictionary d also changed. This means that shallow copying is copying the sequence itself, if there are subsequences in the sequence, it will not be copied. Because there is a subsequence {'name':'Gourd Baby','age': 10,'sex':'男'} in dictionary d, this subsequence is not copied. A feature of shallow duplication at this time.
Another example
lst=[1,2,3,[4,5,6]]
lst2=lst.copy()
print('lst=',lst)
print('lst2=',lst2)
print('lst id=',id(lst))
print('lst2 id=',id(lst2))
lst2[0]=10
lst2[3][0]=100
print('lst=',lst)
print('lst2=',lst2)
print('lst id=',id(lst))
print('lst2 id=',id(lst2))
result
1.3 Traversing the dictionary
Three ways to traverse the dictionary
1.3.1 keys() This method returns all keys of the dictionary
First, we use this method to print all the keys of the dictionary
d={'name':'葫芦娃','age':10,'sex':'男'}
print(d.keys())
The result returned is:
dict_keys(['name', 'age', 'sex'])
This is a type
d={'name':'葫芦娃','age':10,'sex':'男'}
print(type(d.keys()))
What returned is
<class 'dict_keys'>
This is the type of all keys in a dictionary.
Next, we get the keys by traversing the pointer.
d={'name':'葫芦娃','age':10,'sex':'男'}
for k in d:
print(k)
The return value is
name
age
sex
This is all the keys,
so using this feature we can get all the key-value pairs
d={'name':'葫芦娃','age':10,'sex':'男'}
for k in d:
print(k,d[k])
What returned is
name 葫芦娃
age 10
sex 男
1.3.1 values() This method returns a sequence
values() This method returns a sequence, the elements of the sequence are all the values of the dictionary
d={'name':'葫芦娃','age':10,'sex':'男'}
for v in d.values():
print(v)
What returned is
葫芦娃
10
男
Look at the type again
d={'name':'葫芦娃','age':10,'sex':'男'}
print(type(d.values()))
print(d.values())
What returned is
<class 'dict_values'>
dict_values(['葫芦娃', 10, '男'])
It is a type of dictionary value, which stores all the values of the dictionary
1.3.1 items() returns the keys and values of the dictionary
d={'name':'葫芦娃','age':10,'sex':'男'}
print(type(d.items()))
print(d.items())
return value
<class 'dict_items'>
dict_items([('name', '葫芦娃'), ('age', 10), ('sex', '男')])
dict_items is the type of all items in the dictionary,
which returns a dual-valued subsequence, dual-valued, one is the key and the other is the value. You can also traverse this object
d={'name':'葫芦娃','age':10,'sex':'男'}
for k,v in d.items():
print(k,v)
return
name 葫芦娃
age 10
sex 男
What if there is only one variable to receive? try it:
d={'name':'葫芦娃','age':10,'sex':'男'}
for k in d.items():
print(k)
Returns a tuple of two values
('name', '葫芦娃')
('age', 10)
('sex', '男')
See type
d={'name':'葫芦娃','age':10,'sex':'男'}
for k in d.items():
#print(k)
print(type(k))
return
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
2. Collection
2.1 Collection characteristics
- Only immutable objects can be stored in the collection
- The storage objects in the collection are unordered, that is, they are not stored in the order in which the elements are inserted
- No duplicate elements can appear in the collection
2.2 You can view the usage of the collection in the python documentation
2.3 Create a collection
Use braces to create
s={1,2,3,4,5}
print(s,type(s))
return value
{1, 2, 3, 4, 5} <class 'set'>
No duplicate elements
s={1,1,1,2,2,2,3,3,3,4,4,4,5,5,5}
print(s,type(s))
结果是
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201112134258154.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQ2NzM4NDY3,size_16,color_FFFFFF,t_70#pic_center)
只能存储不可变对象,如果存储了可变对象,如列表,就会报错
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201112134455683.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQ2NzM4NDY3,size_16,color_FFFFFF,t_70#pic_center)
#### 2.4 创建空集合要用set()函数
如果有这样一个东西
s={}
它是个字典呢还是集合呢?
The result shows that it is a dictionary type.
If you want to create an empty set, use the set() function
s=set()
print(type(s))
As you can see, the result is a collection type.
The set() function can convert sequences and dictionaries into sets
s=set([1,1,1,2,2,2,3,3,3,34,4,45,5,5,5])
print(s,type(s))
You can see that the list is converted into a collection, and the repeated elements are gone.
If you convert the dictionary to a set, only the keys in the dictionary will be included
# print(s,type(s))
d={'name':'葫芦娃','age':10,'sex':'男'}
s=set(d)
print(s)
The returned result is a collection composed of all keys. It is
not possible to find elements in the collection by index value, because the elements in the collection are unordered.
2.4 Use of collections
The use of a collection is similar to a list dictionary
2.4.1 in与not in
s={1,2,3,'a','b','c'}
print('a' in s)
print(3 not in s)
result
2.4.2 add() adds elements to the collection
s={1,2,3,'a','b','c'}
s.add(10)
s.add(30)
print(s)
result
2.4.3 update() adds elements in one collection to another collection
Add set s2 to set s
s={1,2,3,'a','b','c'}
s2={'王朝','马汉','张龙','赵虎'}
s.update(s2)
print(s)
result
2.4.3 pop() randomly delete an element in the set
After pop() deletes an element, it will return the element
s={1, 2, 'a', 3, '王朝', 'b', '赵虎', 'c', '马汉', '张龙'}
r=s.pop()
print(s)
print(r)
The result is
randomly deleted, 1 is deleted.
2.4.4 remove() deletes the specified element in the collection
Syntax s.remove (elements to be deleted)
s={1, 2, 'a', 3, '王朝', 'b', '赵虎', 'c', '马汉', '张龙'}
s.remove('王朝')
print(s)
result
2.4.5 clear() Clear the collection
Syntax s.clear()
s={1, 2, 'a', 3, '王朝', 'b', '赵虎', 'c', '马汉', '张龙'}
s.clear()
print(s)
return value
set()
Empty collection
2.5 Set operations
2.5.1 Intersection operation
symbol:&
s1={1,2,3,4,5,6,7}
s2={4,5,6,7,8,9,10}
print(s1&s2)
result
2.5.1 Union operation
Symbol: |
s1={1,2,3,4,5,6,7}
s2={4,5,6,7,8,9,10}
print(s1|s2)
result
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
2.5.1 Subtraction operation
symbol:-
s1={1,2,3,4,5,6,7}
s2={4,5,6,7,8,9,10}
print(s1-s2)
2.5.1 Exclusive OR Set Operation
Symbol: ^
XOR operation refers to taking out the elements that both parties do not own to form a set, that is, the disjoint part of the two sets.
s1={1,2,3,4,5,6,7}
s2={4,5,6,7,8,9,10}
print(s1^s2)
result
2.5.1 Check whether a set is a subset or a proper subset of another set
Operator: <=, <
s1={1,2,3,4,5,6,7}
s2={4,5,6,7,}
s3={1,2,3,4,5,6,7}
r1= s2<=s1 # 检验s2是不是s1的子集
r2= s2<s1 # 检验s2是不是s1的真子集
r3= s3<=s1 # 检验s3是不是s1的子集
r4= s3<s1 # 检验s3是不是s1的真子集
print(r1)
print(r2)
print(r3)
print(r4)
Return result
True
True
True
False
2.5.1 Check whether a set is a superset or a true superset of another set
Operator: >=,>
s1={1,2,3,4,5,6,7}
s2={4,5,6,7,}
s3={1,2,3,4,5,6,7}
r1= s1>=s2 # 检验s1是不是s2的超集
r2= s1>s2 # 检验s1是不是s2的真超集
r3= s1>=s3 # 检验s1是不是s3的超集
r4= s1>s3 # 检验s1是不是s3的真超集
print(r1)
print(r2)
print(r3)
print(r4)
Return result
True
True
True
False
3. Functions
A function is also an object, a product of object-oriented programming. Avoid rebuilding wheels. Once a wheel is built, you need to use it everywhere. Moreover, it is convenient (or called maintenance) to modify the program, directly facing our function modification, and all the places where this function is used are modified.
Grammar format
def 函数名(形参1,形参2,......)
代码块
def fn():
print('这是我创建的第一个函数!')
print(fn)
The function as a whole is saved as an object.
If you want to execute a function, just call it, and the calling method is
函数名()
In this example it is
fn()
Result returned
这是我创建的第一个函数!
Remember, fn is a function object, and fn() calls this function.
3.1 Define function
When defining a function, you can define a variable number of formal parameters after the function name. It is equivalent to declaring variables inside the sub-function.
If the function defines the formal parameters when it is defined, the actual parameters must be passed in when the function is called. If there are several formal parameters, then several formal parameters must be passed.
def twosum(a,b):
r=a+b
print(r)
It can be called several times. Remember to pass an equal number of actual parameters when calling.
3.2 How to transfer functions
When defining formal parameters, you can specify default values for the formal parameters. After the default value is specified, if the user passes a parameter, the default value will not work. If the user does not pass a parameter, the default value will take effect.
example:
def fn2(a,b,c=20):
print('a=',a)
print('b=',b)
print('c=',c)
fn2(1,2,3)
fn2(1,2)
3.2.1 Positional parameter transfer
The actual parameters are passed in the order of their formal parameters
.
def fn2(a,b,c):
print('a=',a)
print('b=',b)
print('c=',c)
fn2(1,2,3)
fn2(3,2,1)
result
3.2.2 Keyword parameter transfer
When actually passing parameters, you can also pass parameters according to keywords, regardless of the order.
example:
def fn2(a,b,c):
print('a=',a)
print('b=',b)
print('c=',c)
fn2(1,2,3)
fn2(c=3,b=2,a=1)
result
3.2.3 Mixed parameter transfer
Keyword parameter passing and positional parameter passing can be mixed, but remember that keyword parameters can't be before positional parameters. Otherwise, an error will be reported.
example:
def fn2(a,b,c):
print('a=',a)
print('b=',b)
print('c=',c)
fn2(1,2,a=3)
#fn2(c=3,b=2,a=1)
result