Home > Article > Backend Development > Python's most detailed explanation of data types
Related free learning recommendations: Python Tutorial (Video)
String
The pitfalls of strings:
If there is no double-quoted string in the middle of a triple-quoted string, it will be output as a double in the interpreter Quotation marks
If there is a double quotation mark string in the middle of a triple-quote string, it will be output as a single quotation mark in the interpreter
The string is stored in the memory as
characters String operations:
Input: input()
Output: print()
Index: str[index]
Get address: id(str )
Slicing: str[start: end: step] (negative step size--select in reverse order; the selection direction must be consistent, otherwise the data cannot be selected)
Find: find(): Syntax: str.find(substr, start, end) Note: The return value is the index value of the first occurrence; if the substring does not exist, it returns -1 and no error will be reported.
For example: mystr = 'hello world and itcast and itheima and Python' print(mystr.find('and')) # 12 print(mystr.find('and',15,30)) # 23 print( mystr.find('ands')) # -1 ands substring does not exist index():
Syntax: str.index(substr, start, end) The return value is the first The index value that appears; if the substring does not exist, an error will be reported. For example: mystr = 'hello world and itcast and itheima and Python'print(mystr.index('and')) # 12 print(mystr .index('and',15,30)) # 23print(mystr.index('ands')) #If the index search substring does not exist, an error will be reported count() : Count the number of times a substring appears Syntax: str.index(substr, tart, end) Note: The return value is the number of times the substring appears. If the substring does not exist, it returns 0 and no error is reported. For example: mystr = 'hello world and itcast and itheima and Python' print(mystr.count('and',15,30)) # 1 print(mystr.count('and')) # 3print(mystr .count('ands')) # 0 rfind(): The function is the same as find(), but the search direction starts from the right rindex(): The function is the same as index(), but the search access is from the right Start on the side
Modify:replace(): Replacement syntax: str.replace(old substring, new substring, number of replacements) Note: If you do not write the number of replacements, the default All old substrings will be replaced. If the number of substitutions exceeds the number of occurrences of the substring, the number of substitutions will be the number of occurrences of the substring. After calling the replace function, it is found that the data of the original string has not been modified. The modified data is the return value of the replace function. Description: String is an immutable data type. For example: mystr = 'hello world and itcast and itheima and Python ' new_str = mystr.replace('and','he') new_str = mystr.replace('and','he',1) new_str = mystr.replace('and','he',10) split() : Split syntax: str.split (split character, num) Note: The return value is a list. The missing split character num represents the number of occurrences of the split character, that is, the number of data returned in the future is num 1
For example, mystr = 'hello world and itcast and itheima and Python' list1 = mystr.split('and') list1 = mystr.split('and',2) join():
Merge syntax: character or Substring. join (sequence of multiple characters) Note: Using a substring or substring to merge strings means merging multiple strings into a new string. For example: mylist = ['aa','bb' ,'cc'] new_str = '...'.join(mylist) print(new_str)
Case conversion capitalize(): Convert the first character of the string to uppercase Syntax: str.capitalize( )Note: After the capitalize() function is converted, only the first character of the string will be capitalized, and all other characters will be lowercase.
For example: mystr = 'hello world and itcast and itheima and Python' new_str = mystr.capitalize( ) print(new_str) title(): Convert the first letter of each word in the string to uppercase syntax: str.title()
For example: mystr = 'hello world and itcast and itheima and Python' new_str = mystr .title() print(new_str) lower(): Convert the string from uppercase to lowercase Syntax: str.lower() Note: Convert all to lowercase
For example: mystr = 'hello world and itcast and itheima and Python'new_str = mystr.lower() print(new_str) upper(): Convert the string from lowercase to uppercase Syntax: str.upper() Note: Convert all to lowercase
For example: mystr = 'hello world and itcast and itheima and Python' new_str = mystr.upper() print(new_str)
Delete the leading and trailing spaces lstrip(): Delete the blank characters on the left side of the string Syntax: str.lstrip() For example: mystr = ' hello world and itcast and itheima and Python ' new_str = mystr.lstrip() print(new_str) rstrip(): Delete the whitespace characters on the right side of the string Syntax: str.rstrip()
For example: mystr = ' hello world and itcast and itheima and Python ' new_str = mystr.rstrip() print(new_str) strip(): Delete whitespace characters on both sides of the string Syntax: str.strip()
For example: mystr = ' hello world and itcast and itheima and Python ' new_str = mystr.strip() print(new_str)
String alignment ljust(): Return an original string left-aligned and Use specified characters (default spaces) to fill a new string to the corresponding length. Syntax: str.ljust (length, filling character) For example: mystr = "hello" print(mystr.ljust(10,'.')) The effect is: ' hello....' rjust(): Returns a new string that is right-aligned and filled with specified characters (default spaces) to the corresponding length. Syntax: str.rjust(length, padding characters)
For example: mystr = "hello" print(mystr.rjust(10,'.')) The effect is: '...hello' center(): Returns an original string aligned in the center and using the specified character ( Default space) is padded to the corresponding length of the new string syntax: str.center (length, padding character) For example: mystr = "hello" print(mystr.conter(10,'.')) The effect is: '..hello. ..'
Judge the beginning and end startswith(): Check whether the string starts with the specified substring, if so, return True, otherwise return False. If the start and end position subscripts are set, the syntax is checked within the specified range: str.startswith(substring,start,end)
For example: mystr = 'hello world and itcast and itheima and Python' print( mystr.startswith('hello')) print(mystr.startswith('hel')) print(mystr.startswith('hels')) endswith(): Check whether the string ends with the specified substring, if so, return True , otherwise it returns False. If you set the start and end position subscripts, check the syntax within the specified range: str.endswith(substring,start,end)
For example: mystr = 'hello world and itcast and itheima and Python' print( mystr.endswith('Python')) print(mystr.endswith('Pythons'))
Judge isalpha(): Return True if the string has at least one character and all characters are letters, otherwise return False syntax: str.isalpha() For example: mystr = 'hello world and itcast and itheima and Python' print(mystr.isalpha()) isdigit(): Returns True if the string only contains numbers, otherwise returns False. Syntax: str.isdigit()
For example: mystr1 = '12345' print(mystr1.isdigit()) isalnum(): If the string has at least one character and all characters are letters or numbers Syntax: str.lsalnum ()
For example: mystr2 = 'abc123' print(mystr2.isalnum()) isspace(): If the string contains only blanks, return True, otherwise return False. Syntax: str.isspace()
For example: mystr3 = ' 'print(mystr3.isspace())
List
The pitfalls of lists:
Lists are a type of data structure Specific embodiment
The format of the list [data 1, data 2, data 3]
In work, the list stores the same type of data as much as possible
List operations:
Append(): Append data to the end of the list Syntax: list.append(data) Note: When appending data to the list, the specified data is directly appended to the original list. That is, the original list is modified, so the list is variable type data. If the data appended by append() is a sequence, append the entire sequence to the list
For example: name_list = ['Tom','Lily','Rost'] name_list.append('xiaoming') print( name_list) # Result: ['Tom','Lily','Rost','xiaoming'] extend(): Append data to the end of the list. If the data is a sequence, add the data of this sequence one by one Add to list syntax: list.extend(data)
For example: name_list = ['Tom','Lily','Rost'] name_list.extend('xiaoming') print(name_list) # Result: ['Tom','Lily','Rost','x','i','a',...] insert(): Specify the position to add new data Syntax: list.insert(position Subscript, data) For example: name_list = ['Tom','Lily','Rost'] name_list.insert(1, 'xiaoming') print(name_list) # Result: ['Tom','xiaoming' ,'Lily','Rost']
Determine whether in exists: Syntax: str in list
For example: name_list = ['Tom','Lily','Rost' ] print('Lily' inname_list) # True print('Lilys' in name_list) # Flase not in: Syntax: str not in list For example: name_list = ['Tom','Lily','Rost'] print('Lily' not in name_list) # Flase print('Lilys' not in name_list) # True
Delete del: Syntax: del target example: name_list = ['Tom','Lily','Rost'] del name_list[0] print(name_list) # ['Lily' ,'Rost'] pop(): Delete the data at the specified subscript (default is the last one), and return the data. Whether it is according to the subscript or deleting the last one, the pop function will return the deleted data. Syntax: list .pop()
For example: name_list = ['Tom','Lily','Rost'] del_name = name_list.pop(1) print(del_name) # 'Lily' print (name_list) # ['Tom','Rost']
remove(): Remove the first matching item of a certain data in the list Syntax: list.remove(data)
For example: name_list = ['Tom','Lily','Rose'] name_list.remove('Rose') print(name_list) # ['Tom','Lily'] clear(): Clear the list syntax: list.clear() For example: name_list = ['Tom','Lily','Rost'] name_list.clear() print(name_list) # []
Change and modify the specified subscript data
For example: name_list = ['Tom','Lily','Rost'] name_list[0] = 'aaa'print(name_list) # ['aaa','Lily','Rost'] reverse(): Reverse syntax: list.reverse()
For example: num_list = [1,5,2,3,6, 8] num_list.reverse() print(num_list) # [8,6,3,2,5,1]sort(): Sorting syntax: list.sort(key=None,reverse=False) Note: reverse represents the sorting rule, reverse = True descending order, reverse = False ascending order (default)
For example: num_list = [1,5,2,3,6,8] num_list.sort() print(num_list ) # [1,2,3,5,6,8]
Check index:index(): Returns the index of the location of the specified data--if the data being searched does not If it exists, an error will be reported. Syntax: list.index(data,start,end) For example: name_list = ['Tom','Lily','Rose'] print(name_list.index('Lily',0,2)) # 1 count(): Count the number of times the specified data continues in the current list. Syntax: list.count()
For example: name_list = ['Tom','Lily','Rose'] print (name_list.count('Lily')) len(): Access list length, that is, the number of data in the list. Syntax: len(list)
For example: name_list = ['Tom','Lily', 'Rose'] print(len(name_list)) # 3
Copy copy(): Open up new space to store data Syntax: list.copy() For example: name_list = ['Tom' ,'Lily','Rose'] name_li2 = name_list.copy() print(name_li2) # ['Tom','Lily','Rose']
Traverse while: in sequence Print each data in the list. For example: name_list = ['Tom','Lily','Rose'] i = 0 while i # Result: Tom Lily Rose for: Print each data in the list in sequence. For example: name_list = ['Tom','Lily','Rose'] for i in name_list: print(i) # Result: Tom Lily Rose
Concept of list nesting: List nesting refers to a list that contains other sublists
For example: name_list = [['Xiao Ming','Xiao Hong','Xiao Green'],['Tom','Lily','Rose'],['Zhang San','Li Si', '王二']] print(name_list[2]) # ['Zhang San','Li Si','Wang Er'] print(name_list[2][1]) # Li Si
Tuple
Pitfalls of tuples:
A tuple can store multiple data, but the data in the tuple cannot be modified
Format of tuple: (data 1, data 2, data 3)
If the defined tuple has only one data, it is best to add a comma after the data, otherwise the data type will be unique The data type of this data
At work, tuples store the same type of data as much as possible
Operations of tuples:
Search to find data by subscript: for example :tuple1 = ('aa','bb','cc','bb') print(tuple1[0]) # aaindex(): Find a certain data, if the data exists, return the corresponding Subscript, otherwise an error will be reported. Syntax: The syntax is the same as the index method of lists and strings - tuple.index (substring). For example: tuple1 = ('aa','bb','cc','bb') print(tuple1 .index('aa')) # 0 count(): Count the number of times a certain data appears in the current tuple. Syntax: tuple.count(data) For example: tuple1 = ('aa','bb ','cc','bb') print(tuple1.count('bb')) # 1len(): Count the number of data in the tuple Syntax: len(tuple) For example: tuple1 = ('aa','bb','cc','bb') print(len(tuple1)) # 4
If you modify the direct data in the tuple, an error will be reported immediately. For example: tuple1 = ('aa','bb','cc','bb') tuple1[0] = 'aaa' # Report error If there is a list in the tuple, modify the data in the list. For example: tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30) print(tuple2[2]) # Access the list tuple2[2][0] = 'aaaaa' print(tuple2) # (10, 20, ['aaaaa', 'bb', 'cc'], 50, 30)
Dictionary
Pitfalls of dictionary:
The data in the dictionary appears in the form of key-value pairs. The dictionary data has nothing to do with the data order, that is, the dictionary does not support Subscript, no matter how the data changes later, you only need to find the data according to the name of the corresponding key
The format of the dictionary: {'key1':value1, 'key2':value2}
Dictionary operations:
Add dict[key] = value: Syntax: Dictionary series [key] = value Note: If the key exists, modify the value corresponding to the key. If the key does not exist, add the key value. right. The dictionary is a variable type. For example: dict1 = {'name':'Tom', 'age':20; 'gender':'male'} dict1['name'] = 'Rose' print(dict1) # {'name':'Rose', 'age':20; 'gender':'Male'} dict1['id'] = 110 print(dict1) # {'name':'Tom' , 'age':20; 'gender':'male', 'id':110} dict(zip(list1,list2)): Syntax: dict(zip(list1,list2)) Note: two lists The number of data needs to be the same. For example: a = [1,2,3,4] b = [1,2,3,4] c = dict(zip(a,b)) print(c) # { 1:1, 2:2, 3:3, 4:4}
Delete del()/ del: Delete the dictionary or delete the specified key-value pair in the dictionary Syntax: del dict For example: dict1 = {'name':'Tom', 'age':20, 'gender':'male'} del dict1['gender'] print(dict1) # {'name':' Tom', 'age':20} clear(): Clear the dictionary Syntax: dict.clear() For example: dict1 = {'name':'Tom', 'age':20, 'gender':'Male '} dict1.clear() print(dict1) # {}
Change and modification: Syntax: Dictionary sequence [key] = value Note: If the key exists, modify the value corresponding to the key , if the key does not exist, add this key-value pair. For example: dict1 = {'name':'Tom', 'age':20; 'gender':'male'} dict1['name'] = 'Rose' print (dict1) # {'name':'Rose', 'age':20; 'gender':'Male'}
Search key syntax: dict[key]Note: If the currently searched key exists, the corresponding value will be returned; otherwise, an error will be reported. For example: dict1 = {'name':'Tom', 'age':20; 'gender':'male'} print(dict1['name'] ) # Tomprint(dict1['id']) # Error reporting get() syntax: dictionary sequence.get(key, default value) Note: If the currently searched key does not exist The second parameter (default value) is returned. If the second parameter is omitted, None is returned. For example: dict1 = {'name':'Tom', 'age':20; 'gender':'male'} print( dict1.get('name')) # Tomprint(dict1.get('id',100)) # 100 print(dict1.get('id')) # None keys() syntax: dict.keys() For example: dict1 = {'name':'Tom', 'age':20; 'gender':'male'} print(dict1.keys( )) # dict_keys(['name','age','gender']) values() syntax: dict.values() For example: dict1 = {'name':'Tom', 'age ':20; 'gender':'male'} print(dict1.values()) # dict1.values(['Tom',20,'']) items() syntax: dict1.items ()For example: dict1 = {'name':'Tom', 'age':20; 'gender':'male'} print(dict1.items()) # dict_items([('name',' Tom'),('age',20),('gender','male')])
Traverse the keys of the dictionary, for example, dict1 = {'name':'Tom', 'age':20; 'gender':'male'} for key indict1 .keys(): print(key) # Result: name age gender Traverse the values of the dictionary. For example: dict1 = {'name':'Tom', 'age':20; 'gender':'Male '} for key in dict1.values(): print(key) # Result: Tom 20 Male Traverse the elements of the dictionary. For example: dict1 = {'name ':'Tom', 'age':20; 'gender':'male'} for key in dict1.items(): print(key) # result : ('name','Tom') ('age',20) ('gender','male') Traverse the key-value pairs of the dictionary (unpacking). For example: dict1 = {'name':'Tom ', 'age':20; 'gender':'male'} for key,values in dict1.items(): print(f'{key} = {values} ') # Result: name = Tom age = 20 gender = male
Collection
Pitfalls of collection:
Create a collection using {} or set (), but if you want to create an empty collection, you can only use set(), because using {} creates a dictionary
The collection does not support subscript operations because the collection has no order
The collection data has Deduplication function
Collection operation:
Add data add() syntax: set.add()Note: Because the collection has a deduplication function, , when appending data to the collection is existing data in the current collection, no operation will be performed. For example: s1 = {10,20} s1.add(100) s1.add(10) print(s1) # { 100, 10, 20} update(): Syntax: set.update(list) Note: The appended data is a sequence. For example: s1 = {10, 20} # s1.update(100) # Error report s1.update([100, 200]) s1.update('abc') print(s1) # {'c', 100, 'a', 200, 10, 20, 'b'}
Delete data remove() syntax: set.remove() Note: Delete the specified data in the collection. If the data does not exist, an error will be reported. For example: s1 = {10, 20} s1.remove(10) print(s1) # {20} s1.remove(10) print(s1) # Error report discard() syntax: set.discard() Note: delete the specified data in the collection , no error will be reported if the data does not exist. For example: s1 = {10, 20} s1.discard(10) print(s1) s1.discard(10) print(s1) pop() syntax: set.pop() Note: Randomly delete certain data in the collection and return this data. For example: s1 = {10, 20, 30, 40,50} del_num = s1.pop() print(del_num) print(s1)
Find Data in: Determine that the data is in the set sequence not in: Determine that the data is not in the set sequence. For example: s1 = {10, 20, 30, 40, 50} print(10 in s1) print(10 not in s1)
Public operations
Operator
Operator description Supported container types merge strings, lists, tuples* Copy whether string, list, tuple in element exists string, list, tuple, dictionary, set not in element whether string, list, tuple, dictionary, set does not exist
For example:
# # 1. String str1 ='aa'str2 ='bb'str3 = str1 str2print(str3)# aabb# 2. List list1 = [1, 2]list2 = [10, 20]list3 = list1 list2print(list3)# [1, 2, 10, 20]# 3. Tuple t1 = (1, 2)t2 = (10, 20)t3 = t1 t2print(t3)# (10, 20, 100, 200) # * # 1. String print('-'* 10)# ----------# 2. List list1 = ['hello']print(list1 * 4)# ['hello', ' hello', 'hello', 'hello']# 3. Tuple t1 = ('world',)print(t1 * 4)# ('world', 'world', 'world', 'world')# in or not in # 1. String print('a'in'abcd')# Trueprint('a'notin'abcd')# False# 2. List list1 = ['a','b','c', 'd']print('a'inlist1)# Trueprint('a'notinlist1)# False# 3. Tuple t1 = ('a','b','c','d')print('aa' int1)# Falseprint('aa'notint1)# True
Public method
Function description len() calculates the number of elements in the container del or del() deletes max() returns the elements in the container The maximum value min() returns the minimum value of the element in the container. Range(start, end, step) generates a number from start to end with a step length, which is used by the for loop to use the enumerate() function to convert an available The traversed data objects (such as lists, tuples or strings) are combined into an index sequence, and the data and data subscripts are listed at the same time. It is generally used in for loops.
For example:
# len()# 1. String str1 ='abcdefg'print(len(str1))# 7# 2. List list1 = [10,20,30,40]print(len(list1))# 4 # 3. Tuple t1 = (10,20,30,40,50)print(len(t1))# 5# 4. Set s1 = {10,20,30}print(len(s1))# 3# 5. Dictionary dict1 = {'name':'Rose','age':18}print(len(dict1))# 2# del()# 1. String str1 ='abcdefg'delstr1print(str1)# 2. List list1 = [10,20,30,40]del(list1[0])print(list1)# [20, 30, 40]# max()# 1. String str1 ='abcdefg'print(max(str1 ))# g# 2. List list1 = [10,20,30,40]print(max(list1))# 40# min()# 1. String str1 ='abcdefg'print(min(str1))# a# 2. List list1 = [10,20,30,40]print(min(list1))# 10# range() -- The sequence generated by range() does not contain the end number # 1 2 3 4 5 6 7 8 9foriinrange( 1,10,1): print(i)# 1 3 5 7 9foriinrange(1,10,2): print(i)# 0 1 2 3 4 5 6 7 8 9foriinrange(10): print(i)# enumerate () -- enumerate(traversable object, start=0)list1 = ['a','b','c','d','e']foriinenumerate(list1): print(i)forindex, charinenumerate (list1, start=1): print(f' subscript is {index}, the corresponding character is {char}')
Container type conversion
tuple() function: Convert a sequence into a tuple, for example list1 = [10, 20, 30, 40, 50, 20] s1 = {100, 200, 300, 400, 500} print(tuple(list1)) print(tuple(s1))
List() function: Convert a sequence into a list. For example: t1 = ('a', 'b', 'c', 'd', 'e') s1 = {100, 200, 300, 400, 500} print(list(t1)) print(list(s1))
set() Function: Convert a sequence into a set. For example: list1 = [10, 20, 30, 40 , 50, 20] t1 = ('a', 'b', 'c', 'd', 'e') print(set(list1)) print(set(t1)) # 1. Sets can Quickly complete list deduplication # 2. Sets do not support subscripts
derivatives--generative expressions
List comprehensions function: use an expression Create a regular list or control a regular list. For example: # while loop implementation # 1. Prepare an empty list list1 = [] # Write a loop and append in sequence Numbers are added to the empty list list1 i = 0 while i # for loop implementation list1 = [ ] for i in range(10): list1.append(i) print(list1) # List comprehension implementation list1 = [i for i in range(10)] print(list1) # List comprehension with if # Method 1: range() step size implementation list1 = [i for i in range(0,10,2)] print(list1) # Method 2: List comprehension with if list1 = [ i for i inrange(10) if i % 2 == 0] print(list1) # Multiple for loops to implement list comprehension list1 = [(i, j)fori in range(1, 3)for j in range(3 )] print(list1)
The function of dictionary derivation: quickly merge the list into a dictionary or extract the target data in the dictionary. For example: # 1. Create a dictionary: the key of the dictionary is the number 1-5, value is the square of this number dict1 = {i:i**2 for i in range(1, 5)} print(dict1) # {1 : 1, 2: 4, 3: 9, 4: 16} # 2. Merge the two lists into one dictionary list1 = ['name', 'age', 'gender'] list2 = ['Tom', 20, 'man'] dict1 = {list1[i]: list2[i] for i inrange(len(list1))} print( dict1) # 3. Extract the target data in the dictionary counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99} # Requirement: Extract the dictionary data where the number of computers mentioned above is greater than or equal to 200 count1 = {key: value for key, value in counts.items() if value >= 200} print(count1) # {'MBP':268, 'DELL': 201}
Set derivation function: quickly generate sets, sets There is a data deduplication function, for example: # Create a set, the data is the 2nd power of the list below list1 = [1, 1, 2] list1 = [1, 1, 2] set1 = {i ** 2 for i in list1} print(set1) # {1, 4}
Small integer object pool and large integer in Python Object pool, and the difference between "is" and "=="
Python is a weak variable type language, and there is no need to declare the type of the variable before using it. There are three attributes for a variable: id (memory address), type (variable type), value (value)
The difference between =, ==, and is: = assignment operation, what is passed is id, type, value== determines whether the values are equal is determines whether the ids are equal
Small integer object pool uses object pool technology for small integer objects. Set the range of small integers to [-5,256]. Small integers within this range, any identical integers are the same object. Similarly, the same is true for a single letter. The buffer pool of small integers is created when Python is initialized. The intern mechanism handles spaces and the reuse opportunity of a word. is large, so it is created once. If there are spaces, it is created multiple times. However, if the string length is greater than 20, it is not created once. a = -5 b = -5 a is b # True a = 256 b = 256 a is b # True a = 1000 b = 1000 a is b # True a = 'abc' b = 'abc' a is b # True a = 'helloworld' b = 'helloworld' a is b # True a = 'hello world' b = 'hello world' a is b # False
The large integer object pool exceeds the range of small integers and is a large integer. Each time A new object will be created. But the large integers in a block of code are the same object. The terminal is executed once each time, so the large integer is re-created each time. In pycharm, all codes are loaded into the memory each time it is run and belong to a whole, so there will be a large integer object pool at this time, that is The large integer in a code block is the same object in pycharm. Every time it is run, all the code is loaded into the memory and belongs to a whole, so at this time there will be a large integer object pool, that is, the large integer in a code block It is the same object a = 1000 b = 1000 a is b # False a = -1888 b = -1888 a is b # False class C1(object): a = 100 b = 100 c = 1000 d = 1000 class C2(objcet): a = 100 b = 1000 print(C1.a is C1.b) # True print(C1.a is C1.a) # True print(C1.c is C1.d) # True print(C1.d is C1.b) # Falsec
Generator
The function of the generator is based on the rules set by the programmerGenerate data in a loop, when the conditions are not metGenerate data ends The data is not generated all at once, but using one and generating another one can save a lot of memory
Creation of generators Generator derivation Generator derivation and list derivation Similar, but the list comprehension uses parentheses # to create the generator my_generator = (i * 2 for i in range(5)) print(my_generator)
yield keyword: Characteristics of the yield keyword generator: having the yield keyword in the def function defmygenerator(n): for i in range(n): print('Start generating...') yield i print('Complete once...') Note: When the code is executed to yield, it will pause and then return the result. The next time the generator is started, it will continue to execute the generator at the paused position. If the data is generated and the next data in the generator is obtained again, a StopIteration exception will be thrown. , indicating that there is no exception handling operation inside the while loop, and you need to manually add the exception handling operation. The stop iteration exception is automatically handled inside the for loop, which is more convenient to use.
Generator related functions next functionGet the next value in the generatorfor loopTraverse each value in the generator
Related free learning recommendations:Programming video
The above is the detailed content of Python's most detailed explanation of data types. For more information, please follow other related articles on the PHP Chinese website!