python learning
range() function
range(5) -> 0,1,2,3,4
range(5,9) -> 5,6,7,8
Range (0,10,3) - > 0, 3, 6, 9: step size is 3
list
In memory, a sequence is a continuous memory space used to store multiple values.
An object contains three parts: memory address id, data type type and value. The id of the object is stored in the sequence.
List index, from front to back, subscript from 0, from back to front, subscript from - 1.
list.append(obj) #Add a new object at the end of the list list.extend(seq) #Append multiple values in another sequence at the end of the list at one time (expand the original list with the new list) list.count(obj) #Counts the number of times an element appears in the list list.index(obj) #Find the index position of the first match of a value from the list list.insert(index, obj) #Insert the object into the list index location list.pop([index=-1]) #Removes an element from the list (the default last element) and returns the value of that element list.remove(obj) #Removes the first occurrence of a value in the list list.sort( key=None, reverse=False) #Sort the original list list.clear() #clear list list.copy() #Copy the list and return a shallow copy of the list object list.reverse() #Flip all elements in place
The append() method adds elements in place, and the memory address of the list remains unchanged
>>> list2=[x**2 for x in range(10) if x&1==1] >>> list2 [1, 9, 25, 49, 81] >>> id(list2) 22112552 >>> list2.append(2) >>>> list2 [1, 9, 25, 49, 81, 2] >>> id(list2) 22112552
+The operation uses the new memory address, while the + = operation still uses the original memory address
>>> list3 [1, 2, 3, 4, 5] >>> id(list3) 22111464 >>> list3+=[6] >>> list3 [1, 2, 3, 4, 5, 6] >>> id(list3) 22111464 >>> list3=list3+[7] >>> list3 [1, 2, 3, 4, 5, 6, 7] >>> id(list3) 22069096
The extend() method is an in place operation, and the memory address remains unchanged. The efficiency is higher than that of + operation.
>>> list3.extend([9,10]) >>> list3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> id(list3) 22069096
List deletion:
del delete directly
del list[2]
pop() deletes and returns. If no location is specified, the last element is deleted by default
>>> list4=[1,2,3,4] >>> list4 [1, 2, 3, 4] >>> del list4[2] >>> list4 [1, 2, 4] >>> list4.pop() 4 >>> list4 [1, 2]
The remove() method deletes the specified element that appears for the first time. If it does not exist, an exception is thrown.
>>> list5=[1,2,3,4,5,4,3,2] >>> list5.remove(2) >>> list5 [1, 3, 4, 5, 4, 3, 2] >>> list5.remove(6) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list
List index:
index() method to obtain the location where the specified element appears for the first time, and you can specify the starting address of the search.
def index(self, *args, **kwargs): # real signature unknown """ Return first index of value. Raises ValueError if the value is not present. """ pass >>>list1=[1,2,3,4,5,3,4,6] >>>print(list1.index(3,4))
Do not create a list sorting of new objects:
>>> list6=[1,6,4,9,20,8,3] >>> id(list6) 22112616 >>> list6.sort() >>> list6 [1, 3, 4, 6, 8, 9, 20] >>> id(list6) 22112616 >>> list6.sort(reverse=True) >>> list6 [20, 9, 8, 6, 4, 3, 1] >>> id(list6) 22112616
Out of order:
>>> import random >>> random.shuffle(list6) >>> list6 [3, 8, 20, 4, 1, 6, 9] >>> id(list6) 22112616
Sort() function to generate new objects:
>>> list6=sorted(list6) >>> list6 [1, 3, 4, 6, 8, 9, 20] >>> id(list6) 22036296
List derivation generation
cells = [(row,col) for row in range(1,10) for col in range(1,10)] #You can add two loops, which is actually a nested loop. The cells list contains 9 * 9 tuples
tuple
When a tuple contains only one element, you need to add a comma ',' after the element, otherwise the parentheses will be used as operators.
Tuples can use subscript indexes to access values in tuples.
The element values in tuples are not allowed to be modified, but we can connect and combine tuples.
Element values in tuples are not allowed to be deleted, but we can use del statement to delete the whole tuple.
len(tuple) #Calculate the number of tuple elements. max(tuple) #Returns the maximum value of an element in a tuple. min(tuple) #Returns the minimum value of the element in the tuple. tuple(iterable) #Converts an iteratable series to tuples.
>>>list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>>tuple1=tuple(list1) >>>tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu')
The immutability of tuples refers to the immutability of the contents in the memory pointed to by tuples.
Immutable objects, such as tuples, which contain variable objects, such as lists, the modification of the contents of the lists is legal. The tuple stores the memory address of the list, and the change of the list element does not change its own address.
Tuple sorting can only use the sorted() function, and the return type is list
>>> tup=(1,5,4,9,8,7,3,6) >>> id(tup) 21784752 >>> type(tup) <class 'tuple'> >>> list=sorted(tup) >>> id(list) 22112616 >>> type(list) <class 'list'> >>> list [1, 3, 4, 5, 6, 7, 8, 9]
zip() function:
>>> list1=[1,2,3] >>> list2=[10,20,30] >>> list3=[100,200,300] >>> zip_tup=zip(list1,list2,list3) >>> type(zip_tup) <class 'zip'> >>> list(zip_tup) [(1, 10, 100), (2, 20, 200), (3, 30, 300)]
Generator derivation (used to generate tuples)
>>> (x for x in range(1,100) if x%0==0) <generator object <genexpr> at 0x013269C8>
The derivation results in a generator object.
A generator can only run once.
>>> generator = (x for x in range(1,100) if x%3==0) >>> tup1=tuple(generator) >>> tup1 (3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99) >>> tup2=tuple(generator) >>> tup2 ()
Dictionaries
- Accessing values in the dictionary
Put the corresponding key in square brackets, as shown in the following example:
tinydict = {'Name': 'xiaoming', 'Age': 10, 'Class': 'First'} print ("tinydict['Name']: ", tinydict['Name']) print ("tinydict['Age']: ", tinydict['Age'])
Operation results:
tinydict['Name']: xiaoming tinydict['Age']: 10
- Create an empty dictionary with braces {}
# Use braces {} to create an empty dictionary emptyDict = {} # Print Dictionary print(emptyDict) # View the number of dictionaries print("Length:", len(emptyDict)) # View type print(type(emptyDict))
Operation results:
{} Length: 0 <class 'dict'>
- The method to add new content to the dictionary is to add new key / value pairs, modify or delete existing key / value pairs, as shown in the following examples:
tinydict = {'Name': 'xiaoming', 'Age': 10, 'Class': 'First'} tinydict['Age'] = 8 # Update Age tinydict['School'] = "One middle school" # Add information print ("tinydict['Age']: ", tinydict['Age']) print ("tinydict['School']: ", tinydict['School'])
- You can delete a single element or empty the dictionary. Emptying requires only one operation. Explicitly delete a dictionary with the del command
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} del tinydict['Name'] # Delete key 'Name' tinydict.clear() # Empty dictionary del tinydict # Delete dictionary tinydict.pop('Name') #Delete key value pairs and return values print ("tinydict['Age']: ", tinydict['Age']) print ("tinydict['School']: ", tinydict['School'])
- The dictionary value can be any python object, either standard or user-defined, but the key does not work.
Two important points to remember:
1) The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered
tinydict = {'Name': 'Lisa', 'Age': 26, 'Name': 'lisa'} print ("tinydict['Name']: ", tinydict['Name'])
Operation results:
tinydict['Name']: lisa
2) Keys must be immutable, so you can use numbers, strings or tuples as keys, but not lists. For example:
tinydict = {['Name']: 'Runoob', 'Age': 7} print ("tinydict['Name']: ", tinydict['Name'])
Output results of the above examples:
Traceback (most recent call last): File "C:/Users/11457/Desktop/pythonProject1/practise.py", line 1, in <module> tinydict = {['Name']: 'Runoob', 'Age': 7} TypeError: unhashable type: 'list'
- Correlation function:
len(dict) #Calculate the number of dictionary elements, that is, the total number of keys. str(dict) #Output dictionary, a string representation that can be printed. dict.update(dict2) #Update the key value pair of dict2 to dict
The core of the dictionary object is the hash table.
Dictionary traversal is separated from dictionary modification. Adding new key value pairs may lead to dictionary expansion and rearrangement of key value pairs.
Dictionary derivation
>>> my_text='i love you,i love him,i love all people.' >>> char_count={c:my_text.count(c) for c in my_text} >>> char_count {'i': 4, ' ': 7, 'l': 6, 'o': 5, 'v': 3, 'e': 5, 'y': 1, 'u': 1, ',': 2, 'h': 1, 'm': 1, 'a': 1, 'p': 2, '.': 1}
aggregate
The underlying implementation of a collection is a dictionary, which is actually a key object in the dictionary.
Set set1 and set2:
Union
set1|set2
intersection
set1&set2
Difference set
set1-set2
Set derivation generation
>>> set1={x for x in range(1,100) if x%11==0} >>> set1 {33, 66, 99, 11, 44, 77, 22, 55, 88}
character string
String slicing
s='abcdef'
>>> s[2:] 'cdef'
>>> s[2:5] 'cde'
>>> s[:-2] 'abcd'
>>> s[::-1] 'fedcba'
split() function
>>> str='i am a teacher' >>> str 'i am a teacher' >>> str.split() ['i', 'am', 'a', 'teacher'] >>> str.split('a') ['i ', 'm ', ' te', 'cher']
join() function
>>> str=['as','bg','DG','Ui'] >>> '*'.join(str) 'as*bg*DG*Ui' >>> ''.join(str) 'asbgDGUi' >>> ' '.join(str) 'as bg DG Ui'
+When you operate a string, you can generate several new string objects. The performance of join() is good.
String resident mechanism
>>> a='abc123' >>> b='abc123' >>> print(id(a),id(b)) 30500256 30500256
correlation function
>>> str1='I am mary,I'm very happy to be here today.' >>> str1.startswith('I') #Judge whether to start with 'I' True >>> str1.endswith('Heart.') #Judge whether to "heart." end True >>> str1.find('I') #Where 'I' first appeared 0 >>> str1.rfind('I')#Where did 'I' last appear 9 >>> str1.find('s') #Query the position of non-existent characters and return - 1 -1 >>> len(str1) #String length 19 >>> str1.isalnum() #Strings are all letters and numbers False >>> str1.isalpha() #Strings are all letters False >>> str1.count('I')#Statistics' I 'appeared several times 2 >>> ' acount number '.strip() #Remove leading and trailing spaces 'acount number' >>> ' acount number '.lstrip() #Remove header space 'acount number ' >>> ' acount number '.rstrip() #Remove trailing spaces ' acount number' >>> '**#$asdfghk%^*'.strip('*') #Remove head and tail '*' '#$asdfghk%^'
toggle case
>>> str2='i like my home' >>> str2.capitalize() #Generates a new string, capitalized 'I like my home' >>> str2.title() #Generates a new string with the first letter of each word capitalized 'I Like My Home' >>> str2.upper() #Generates a new string with each letter capitalized 'I LIKE MY HOME' >>> str3='I LIKE MY HOME' >>> str3.lower() #Generates a new string, each letter lowercase 'i like my home' >>> str4='I LiKe My HouSE' >>> str4.swapcase() #Generate a new string and change the case of all letters 'i lIkE mY hOUse'
Formatting of strings
format() function
Variable string StringIO
>>> import io >>> s='hello,world' >>> sio=io.StringIO(s) >>> sio <_io.StringIO object at 0x017B8898> >>> sio.getvalue() 'hello,world' >>> sio.seek(7) 7 >>> sio.seek(0) 0 >>> sio.write('H') 1 >>> sio.getvalue() 'Hello,world'
##Operator
| #Bitwise OR & #Bitwise AND ^ #Bitwise XOR ~ #Flip by bit << #Left shift >> #Right shift / #except // #Divisible + #Number addition; String splicing; List and tuple merging * #Digital multiplication; String copy; List and tuple replication
function
To use global variables in a function, you need to declare them with global first.
The query and access speed of local variables is higher than that of global variables.
Parameter transfer
Everything in python is an object, and all parameter passing is' reference passing ', and there is no' value passing '.
b=[10,20,30] print("b:",id(b)) def funcb(m): print("m:",id(m)) m.append(40) funcb(b) print(b) print('b:',id(b))
Operation results:
b: 25339368 m: 25339368 [10, 20, 30, 40] b: 25339368
When an object of immutable type is passed, it is still passed by reference. When the object is modified in the function, a new object is created.
a=10 print("a:",id(a)) def funcb(m): print("m:",id(m)) m+=1 print("m:",id(m)) funcb(a)
result:
a: 1682950208 m: 1682950208 m: 1682950224
The default value parameter should be placed at the end of the formal parameter list.
Shallow copy and deep copy
Shallow copy: do not copy the contents of the shell object, but only the reference of the shell object.
Deep copy: copy all the memory pages of the child object, and the modification of the child object will not affect the source object.
When passing an immutable object, if a copy occurs (during assignment), it is a shallow copy.
Shallow copy sample code:
import copy a=[10,20,[30,40]] b=copy.copy(a) print('a',a,id(a)) print('b',b,id(b)) b.append(50) b[2].append(0) print('---Shallow copy---') print('a',a,id(a)) print('b',b,id(b)) result: ```python a [10, 20, [30, 40]] 29937256 b [10, 20, [30, 40]] 29937064 ---Copy--- a [10, 20, [30, 40, 0]] 29937256 b [10, 20, [30, 40, 0], 50] 29937064
Deep copy sample code:
import copy a=[10,20,[30,40]] b=copy.deepcopy(a) print('a',a,id(a)) print('b',b,id(b)) b.append(50) b[2].append(0) print('---Deep copy---') print('a',a,id(a)) print('b',b,id(b))
result:
a [10, 20, [30, 40]] 27446888 b [10, 20, [30, 40]] 27446696 ---Deep copy--- a [10, 20, [30, 40]] 27446888 b [10, 20, [30, 40, 0], 50] 27446696
Variable parameters and forced named parameters
There are two kinds of variable parameters. One is * param, which collects arguments into tuples; The second is * * param, which collects arguments into the dictionary.
*param:
def func1(a,b,*c): print(a,b,c) func1(1,2,3,4,5,6,'a')
Operation results:
1 2 (3, 4, 5, 6, 'a')
**param:
def func1(a,b,**c): print(a,b,c) func1(1,2,name='zzq',age=19,school='dlut')
Operation results:
1 2 {'name': 'zzq', 'age': 19, 'school': 'dlut'}
Nested function
nonlocal declares an outer local variable that can be modified later.
Global declares a global variable, which can be modified later.
yield keyword
Return with yield instead of return. The function returns a generator.
Iterators and iteratability
Iterator: an object that can be accessed with next() and continuously returns the next value.
Interoperable: iteratability
Interaor: iterator
Collection class objects (list,str,tuple,dict) and generators are iteratable, but not necessarily iterators.
iter() function: to change an iterative object into a generator object, you can use the next() function.
closure
Is a special function, which is very special when created.
Is an important way of functional programming.
Create closure:
- Nested function definition (internal function, external function).
- Internal functions use variables defined in external functions.
- The external function must have a return value and return the name of the internal function.
Simple example:
def funcOut(num1): def funcIn(num2): return num2+num1 return funcIn if __name__ == '__main__': a=10 b=20 f=funcOut(a) print(type(f)) print(f(b)) print(f(100))
<class 'function'> 30 110
The local variable of an external function does not disappear with the end of the external function call.
Special uses of closures:
- You can add new functions without modifying the existing function source code. For example:
Log function (Statistics of access events, access function, writing to log file), permission verification
External declaration
global: global declaration
nonlocal: external declaration
Classes and objects
new() method: creates an object, which generally does not need to be rewritten
init() method: initializes the created object, which generally needs to be rewritten by yourself
Private property
class Employee: def __init__(self,name,age): self.name=name self.__age=age #Attribute preceded by _, Represents private e=Employee('xiaoming',18) print(e.name) print(e._Employee__age) #Format for accessing private properties outside the class
Operation results:
xiaoming 18
The private property of the parent class, and the child class also needs indirect access.
combination
class A: def say(self): print('AAA') class B: def __init__(self,a): self.a=a a=A() b=B(a) b.a.say()
Operation results
AAA
Modules and packages
__ init__.py: when the module in the package is used for the first time__ init__. The PY module executes once.