This paper summarizes the basic data types in python language, including (int,bool,str,list,tuple,set,dict,none,float) data type methods (unique functions, public functions).
Although the content is numerous and cumbersome, you only need to remember the common knowledge points. (article 2W words, according to the directory index)
Structure: Data type. Function name (...) (n for number; x for string; i for index; k for key; v for value)
catalogue
data type | Definition and conversion | Can I index | Can I modify / hash(x) | Other features | distinguish | |
---|---|---|---|---|---|---|
integer | int | a = int() | Immutable (hashable) | Decimal integers | The smallest unit in which individual data is stored. Immutable type internal data cannot be modified. | |
Boolean | bool | a = bool() | Immutable (hashable) | Indicates True / False | ||
character string | str | a = str() | Orderly | Immutable (hashable) | Information in quotation marks | |
list | list | a = list() a = [] | Orderly | Variable (non hashable) | Orderly: you can index slicing operations and put them first. Variable: modifiable | Container for storing multiple data. Variable type internal data can be modified (added, deleted, modified) |
tuple | tuple | a = tuple() a = ( ,) | Orderly | Immutable (hashable) | Add "," after the last element to identify the tuple. | |
aggregate | set | a = set() | disorder | Variable (non hashable) | (child) elements must be hashable, and elements cannot be duplicated (de duplicated). | |
Dictionaries | dict | a = dict() a = {} | disorder | Variable (non hashable) | The key must be hashable, the key is not repeated, and the element is stored in the form of key value pair. (concise format) | |
empty | None | a = None | Indicates "null"“ | |||
floating-point | float | a = float() | Represents a decimal |
Add: for immutable type (str), the original value cannot be modified, and the new value can only be defined through the newly created data. As long as it is ordered, it can be obtained through index. Similarly, it can be obtained through slice;
For a variable type (list), it is generally not created, and the original value can be directly modified; as long as it is ordered, it can not only be accessed (read) through the index, but also be modified and deleted. Similarly, it can be modified and deleted through the slice value;
Unordered data types cannot be indexed, but dictionaries can be indexed by keys.
##Using in to check whether the elements are in the list and tuple can only be compared many times one by one, which is very inefficient;
##Compared with set,dict will be faster, converted to hash value and compared once, which is more efficient.
Any type can be converted to bool type: 0, '' (empty string), None, empty container is false; others are true.
int type
Unique features:
value = 12 print(bin(value)) #Binary representation of the output value #0b1100 num = value.bit_length() #How many bits does the binary of the value have print(num) #4
Public function: addition, subtraction, multiplication and division
bool type
No special unique function;
Public function: addition, subtraction, multiplication and division
v1 = True + True #True is 1, False is 0, and the operation is repeated print(v1) #2
str type
Unique features:
There are about 48. Here are 22 common ones:
1, Judge whether the string starts with xx,. Startswitch (xx)
2, Judge whether the string starts with xx,. Endswitch (xx)
#Judge whether they are from Western Shaanxi and rural areas. text = input('Please enter your hometown:') #Input: Hengshan District, Yulin City, Shaanxi Province if text.startswith('Shaanxi'): #Determine whether the string starts with xx #if True, execute the following output statement print('Are you from Shaanxi') if text.endswith('village' or 'team'): #Determine whether the string ends with xx #if False does not execute the output statement print('Are you from the countryside')
3, Judge whether the string is a decimal number,. isdecimal()
#Enter two numbers to add num1 = input('Please enter a number:') num2 = input('Please enter a number:') if num1.isdecimal() and num2.isdecimal(): #Determines whether the string is a decimal number print(int(num1)+int(num2)) else: print('Input error') #. isdigit() will judge that ① is also True
4, Remove the spaces on both sides of the string,. strip()
5, Remove the space to the left of the string,. lstrip()
6, Remove the space to the right of the string,. rstrip()
7, Remove the contents specified on both sides (left and right) of the string,. strip('xx ')
text = ' Lin Bei is a handsome man ' print(text.strip()) #Remove spaces on both sides print(text.lstrip()) #Remove the space on the edge of the zuo print(text.rstrip()) #Remove the space on the edge of you print(text.strip('Handsome boy ')) #Remove the specified xx content on both sides #Output: (* for space position) ''' Lin Bei***It's a*Handsome boy Lin Bei***It's a*Handsome boy** **Lin Bei***It's a*Handsome boy Lin Bei***It's a* '''
8, Change letters to uppercase,. upper()
9, Change letters to lowercase,. lower()
10, Capitalize the first letter,. capitalize()
#Complete the judgment of the verification code (case insensitive) and remove the spaces entered incorrectly code = input('Please enter the verification code:') #Input: heLIN date = code.strip() #Remove spaces on both sides value = date.upper() #Change the original string letter to uppercase print(value) #HELIN if value == 'HELIN': print('Validation succeeded') else: print('Validation failed') value = code.strip().lower() #Changes the original string letter to lowercase print(value) #helin value = value.capitalize() #Change the initial of the original string to uppercase print(value) #Helin
11, Replace the contents of the string. Replace A of the string with B,. replace('A','B ')
#Complete the replacement of sensitive words name = input('Please enter a comment:') value = name.replace('sb', '**') #Replace a in the string with b value = value.replace('cao', '***') print(value) #Complete the replacement of multiple sensitive words name = input('Please enter a comment:') char_list =['sb','cao','horse','grass','board'] for i in char_list: name = name.replace(i, '**') print(name)
12, The string content is divided into (list). The content in the string is divided according to 'XX'. split('xx ')
13, Number of cuts from the left,. Spit ('x ', n)
14, Number of cuts from the right,. rspilt('x',n)
#Cut the string according to ',' info = 'Please call,I,Male god' user_list = info.split(',') #Split the contents of the string according to 'xx' print(user_list) #['please call', 'I', 'male god'] print(user_list[2]) #Male god value = info.replace(',', '|') print(value) #Please call me male god result = value.split('|',1) #Cut once print(result) #['please call', 'I'm a male god'] result = value.rsplit('|',1) #Cut the string from the right once print(result) #['please call me', 'male god'] #View file suffix file_path = 'D:\lx\study_python.py' print(file_path.rsplit('.',1)[1]) #py
15, Splice a sequence (list) into a string, splice a list into a string through 'x', and 'x'.join(list)
user_list = ['Please call', 'I', 'Male god'] result = ''.join(user_list) #Concatenate lists into strings print(result) #Please call me male god
16, Format of string,. format(...)
text = '{}It's Chinese{},to{}Return in.' print(text.format('Taiwan','A provincial administrative region',2021)) #Splicing with text as template print(text.format('Hong Kong','special administrative region',1997)) print(text.format('Macao','special administrative region',1999)) #Taiwan is a provincial administrative region of China and will return in 2021. #Hong Kong, a special administrative region of China, returned to China in 1997. #Macao, a special administrative region of China, returned to China in 1999.
17, Convert string to bytes,. encode()
18, Convert bytes to strings,. decode()
date = 'character string bite' transform = date.encode('utf-8') #Convert string to byte type print(transform) #b'\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2bite' #utf-8\gbk encoding is stored on hard disk (file, network), byte type old = transform.decode('utf-8') #Convert bytes to bytes print(old) #String bite #unicode encoding is stored in memory, string type
19, Center of string,. center(n,x)
20, String left,. ljust(n,x)
21, String right,. rjust(n,x)
#The center of the string, left and right title = 'Long live Lin Bei' date = title.center(20,'*') #String content centered print(date) #********Long live Lin Bei******** date = title.ljust(20,'-') #String content left print(date) #Long live Lin Bei---------------- date = title.rjust(20,' ') #String content right print(date) # Long live Lin Bei
22, Fill the front edge of the string with 0,. zifill(n)
#The binary number is displayed as 1 byte date = '101' result = date.zfill(8) #Fill n '0' before string print(result) #00000101
Public functions:
1, Add, # String splicing
v1 = 'Lin Bei' + 'yyds' print(v1) #Lin Bei yyds
2, Multiply and # repeat the string n times
v2 = 'yyds' * 3 print(v2) #yydsyydsyyds
3, Find the length, # get the string length, len()
v3 = 'Lin Bei yyds' print(len(v3)) #6
4, Index, (get characters in string)
text = 'With great power there must come great responsibility.' #print(text[0])#desire #print(text[-1])#heavy #Traversal (= index + loop) index = 0 while index < len(text): print(text[index]) index += 1 #Traversal (reverse order) index = len(text) - 1 while index >= 0: print(text[index]) index -= 1
5, Slice, (get substring (multiple characters) in string)
massage = 'Love beauty, love talent' # print(massage[0:4])#Love beauty # print(massage[-4:len(massage)])#Love in talent #Cannot modify, can create result = massage[0:2] + 'level of appearance' + massage[5:7] + 'ability' print(result)#Like beauty, love ability
6, Step size, (jump to get string content)
name = 'May you go out of your life and return as a teenager.' print(name[::2]) #Willing to walk for half a year print(name[-1:0:-1]) #. When you are young, you still come back and leave half your life
#Implement string inversion print(name[::-1])#. Young is still coming back, half a life away, would you like to
7, Loop through the string. In addition to the while + index method above, there is also a for + variable, and for+range() gets the index.
text = 'With great power there must come great responsibility.' #for loop, variable receiving for item in text: print(item) #for + range(), create a list for index in range(len(text)): #print(index)#Index subscript of string print(text[index])
list type
Unique features:
1, Append, add an element at the end of the list,. append(x)
'''Understand that lists are ordered and variable''' user_list = [] user_list.append('Football') #Put element x in the list print(user_list)#['football'] user_list.append('badminton') print(user_list)#['football', 'badminton'] user_list.append('Swimming') print(user_list)#['football', 'badminton', 'swimming'] user_list = [] print(user_list)#[]
#Users enter hobbies and put them into the list (enter q to exit) user_list = [] while True: hobby = input('Please enter your hobby(Q\q Exit:') if hobby.lower() == 'q': break user_list.append(hobby) print(user_list)
#Comprehensive case, input the number of players and everyone's name, put them into the list and output welcome = 'Welcome nb game' print(welcome.center(30,'*')) #The user inputs a value to determine whether it is a number. If yes, it will be converted to shaping; No output error while True: num = input('Please enter the number of games:') if num.isdecimal(): user_count = int(num) break else: print('Input error') #Output value massage = '{}People participate in the game'.format(user_count) print(massage) #Enter the player's name and put it in the list name_list = [] for i in range(1,user_count + 1): player = 'Please enter player name({}|{}):'.format(i,user_count) name = input(player) name_list.append(name) print(name_list) ''' ***********Welcome nb game*********** Please enter the number of games:3 3 People participate in the game Please enter player name (1)|3):The little tigers Please enter player name (2)|3):beyond Please enter player name (3)|3):Phoenix Legend ['The little tigers', 'beyond', 'Phoenix Legend'] '''
2, Batch append, adding one list to another,. extend(list)
user_list = [11,22,33] date_list = ['aa','bb'] user_list.extend(date_list) #Add list to new list print(user_list) #[11, 22, 33, 'aa', 'bb'] date_list.extend(user_list) print(date_list) #['aa', 'bb', 11, 22, 33]
#for loop list +. Append() = =. Extend() user_list = [11,22,33] date_list = ['aa','bb'] for i in date_list: user_list.append(i) print(user_list) #[11, 22, 33, 'aa', 'bb']
3, Insert, insert the X element at the specified position (index i) in the list,. insert(i, x)
user_list = ['Wang Baoqiang','article','Deng Chao'] user_list.insert(1,'Hu Ge') #Insert the x element where the index of the original list is i print(user_list) #['Wang Baoqiang', 'Hu Ge', 'article', 'Deng Chao'] user_list.insert(0, 'Wu Jing') print(user_list) #['Wu Jing', 'Wang Baoqiang', 'Hu Ge', 'article', 'Deng Chao'] '''No error will be reported for non-existent indexes. Indexes less than 0 are placed at the head of the list; indexes greater than the length of the list are placed at the end of the list.'''
#The user enters the name (q exit), and the one starting with 'Dragon' is placed at the head of the list; otherwise, it is placed in order user_list = [] while True: name = input('Please enter your name( Q\q Exit:') if name.upper() == 'Q': break if name.startswith('Loong'): user_list.insert(0,name) else: user_list.append(name) print(user_list)
4, Delete, delete the first X element in the list from left to right,. remove(x)
user_list = ['First prize: Huawei p40','Second prize: Xiaomi 11','Third prize: Xiaomi Bracelet','Participation Award: water cup'] user_list.remove('Third prize: Xiaomi Bracelet') #Deletes the first x element in the list print(user_list) #['first prize: Huawei p40', 'second prize: Xiaomi 11', 'participation prize: water cup'] '''Nonexistent elements will report errors, so you can(if...in...)Delete after judgment, You can delete multiple elements through(while...else...)Circular judgment'''
#Lottery procedure import random user_list = ['First prize: Huawei p40','Second prize: Xiaomi 11','Third prize: Xiaomi Bracelet','Participation Award: water cup'] while user_list: #Judge that the user_list is not empty name = input('Please enter your name:') value = random.choice(user_list) #random.choice() randomly selects an element from the user_list print('{}win a lottery{}'.format(name, value)) user_list.remove(value) #After drawing out, delete the prize
5, Delete, delete the elements in the list according to the index i,. pop(i)
#Index delete element user_list = ['Liu Yifei','anglebaby','Zhou Dongyu','Yang Zi','Jia Ling'] user_list.pop(1) #Remove the element with index position i from the list print(user_list) #['Liu Yifei', 'Zhou Dongyu', 'Yang Zi', 'Jia Ling'] value = user_list.pop() print(value) #Jia Ling '''()If you do not write, delete the last one by default Deleted elements can be assigned to variables'''
#Queue up to buy train tickets. Those in front of the queue buy tickets first user_list = [] while True: name = input('Please enter the buyer's name: (1 exit)') if name == '1': break user_list.append(name) ticket_count = 3#Remaining votes for i in range(ticket_count): user_name = user_list.pop(0) massage = '{}Ticket purchase succeeded'.format(user_name) print(massage) faild_user = ','.join(user_list) text = '{}Ticket purchase failed'.format(faild_user) print(text)
6, Clear list,. clear()
user_list = ['ll','hh','fool',11,456,'bb'] user_list.clear() #Clear all elements in the original list print(user_list) #[]
7, Get the index according to the value. The index corresponding to the first X element from left to right,. index(x)
user_list = ['ll','hh','fool',11,456,'ll'] index = user_list.index('ll') #Gets the index value whose first element in the list is x print(index) #0 '''Nonexistent elements will report errors, so you can(if...in...)Get index after judgment'''
8, Sort list elements,. sort()
num_list = [26,62,5,8,-3,99,1] num_list.sort() #The default is sort from small to large print(num_list) #[-3, 1, 5, 8, 26, 62, 99] num_list.sort(reverse=True) #Sort from large to small print(num_list) #[99, 62, 26, 8, 5, 1, -3]
# Underlying principle: strings are sorted by alphabetic unicode encoding user_list = ['ll','hh','fool','aa','ll'] user_list.sort() print(user_list) #['AA', 'HH','ll ','ll', 'fool'] #Convert string to unicode code word = 'lh silly al' un_list = [] for char in word: un = ord(char) #unicode decimal representation of a string un_list.append(un) #print(un) #print(hex(un)) #Convert to hexadecimal #print(bin(un)) #Convert to binary print(un_list) # [108, 104, 20667, 97, 108] '''##When both int and str types exist in the list, the order cannot be compared and an error will be reported. However, bool and int can be compared. ''
9, List inversion,. reverse()
user_list = ['ll','hh','fool','aa','ll'] user_list.reverse() #Inversion of list print(user_list) #['ll ',' AA ',' fool ',' HH ','ll']
Public functions:
1, Add, # Splicing of lists
#Add to generate a new list, and the original list remains unchanged. value1 = ['Messi','C Luo'] value2 = ['Peerless double pride'] value = value1 + value2 print(value) #['Messi', 'Ronaldo', 'peerless double pride']
2, Multiply and # repeat the list elements n times
#Multiply to generate a new list, and the original list remains unchanged num_list = [1,2,3] new_list = num_list * 3 print(new_list) #[1, 2, 3, 1, 2, 3, 1, 2, 3]
3, Get the length, # get the number of list elements,. len()
text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] print(len(text_list)) #5
4, The operator contains (in) \ (not in) to determine whether the element is in the container (list/str).
#Determine whether the element is in the list text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] result = 'Zhou Xingchi' in text_list print(result) #True #Determine whether the element is in the string text = 'How are you' result = 'good' in text print(result) #True
#It is generally used with if text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] if 'Meng Da Wu' not in text_list: print('Uncle DA has gone') else: print('Uncle Da, you stayed in the movie.') text_list.remove('Meng Da Wu') #Delete elements through remove() #print(text_list) if 'Meng Da Wu' not in text_list: print('Uncle DA has gone') else: print('Uncle Da, you stayed in the movie.') index = text_list.index('Meng Da Wu') text_list.pop(index) #Get the index through index() and delete it through pop() #print(text_list)
#Sensitive word substitution name = input('Please enter your first name:') forbidden_list = ['horse','grass','board'] for item in forbidden_list: name = name.replace(item, '**') #name.replace(item, '**')#The original name will not be changed. It will only be changed by assigning a value to name. print(name)
##Using in to check whether the elements are in the list can only be compared one by one, which is very inefficient. (compared with set,dict will be faster)
5, Index, (get an element in the list)
text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] #Read data print(text_list[0])#Lau Andy '''If the index position does not exist, an error will be reported''' #Modify data text_list[0] = 'Huazi' print(text_list)# ['Huazai', 'Stephen Chow', 'Chow Yun Fat', 'Zhang Hanyu', 'Wu Mengda'] #Delete data del text_list[4] print(text_list)# ['Huazai', 'Stephen Chow', 'Chow Yun Fat', 'Zhang Hanyu'] '''Use keywords del(delete),Can be based on list Element index position deletion (different from pop,Deleted elements can also be assigned) (Different from remove,(delete by element)'''
6, Slice, (get multiple elements in the list and get the sub list)
text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] #read print(text_list[0:3])#['Andy Lau', 'Stephen Chow', 'Chow Yun Fat'] '''No error will be reported if the slice position does not exist''' #modify text_list[3:5] = ['Xue You Zhang','Guo Fucheng','dawn','Chao Wei Liang'] print(text_list)#['Andy Lau', 'Stephen Chow', 'Chow Yun Fat', 'Zhang Xueyou', 'Guo Fucheng', 'Liming', 'Liang Chaowei'] #delete del text_list[1:] print(text_list)#['Andy Lau']
7, Step size, (jump to get the contents of the list)
text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] print(text_list[0:4:2]) #['Andy Lau', 'Chow Yun Fat'] print(text_list[-1:1:-1]) #['Wu Mengda', 'Zhang Hanyu', 'Zhou Runfa']
#Inversion of list new = text_list[::-1] #Slice inversion to get a new list, the original unchanged print(new) #['Wu Mengda', 'Zhang Hanyu', 'Zhou Runfa', 'Zhou Xingchi', 'Liu Dehua'] '''Different from reverse(),Modify the original data directly'''
8, for loop list
text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] #A for loop that receives elements with variables for item in text_list: print(item) #for+range(), accept index with variable for index in range(len(text_list)): print(text_list[index])
#Pit: in the list cycle, when the data is deleted while taking values through the index, there will be confusion (the element subscript is not in the original index position) #(it can be deleted by reverse retrieval without affecting the original index) text_list = ['Lau Andy','Zhou Xingchi','Zhou Runfa','Zhang Hanyu','Meng Da Wu'] for item in range(len(text_list)-1,-1,-1): if text_list[item].startswith('week'): text_list.pop(item) print(text_list) #['Andy Lau', 'Zhang Hanyu', 'Wu Mengda']
tuple type
Unique features:
Tuples are ordered, immutable types. No unique features.
Tuples are immutable, but when a list is nested inside a tuple, the nested list can be changed.
Tuples are immutable (i.e. fixed tuples). When variables are put into tuples, it is equivalent to dynamic tuples.
Public functions:
1, Add, # Splicing of tuples
#Add to generate a new tuple, and the original tuple remains unchanged. delicious = ('Mutton noodles','Haggis','Chinese hamburger','Pita Bread Soaked in Lamb Soup') food = ('Hengshan spicy sausage','Cold Noodles with Sesame Sauce') result = delicious + food print(result) #('mutton noodles',' mutton offal ',' roujiamo ',' mutton paomo ',' Hengshan spicy sausage ',' cold noodles')
2, Multiply and # repeat n-dimensional group elements
#Multiply to generate a new tuple, and the original tuple remains unchanged. food = ('Hengshan spicy sausage','Cold Noodles with Sesame Sauce') print(food * 2) #('Hengshan spicy sausage', 'cold noodles',' Hengshan spicy sausage ',' cold noodles')
3, Get the length, # get the number of tuple elements,. len()
result = ('Mutton noodles', 'Haggis', 'Chinese hamburger', 'Pita Bread Soaked in Lamb Soup', 'Hengshan spicy sausage', 'Cold Noodles with Sesame Sauce') print(len(result)) #6
4, Index, (get an element in a tuple)
result = ('Mutton noodles', 'Haggis', 'Chinese hamburger', 'Pita Bread Soaked in Lamb Soup', 'Hengshan spicy sausage', 'Cold Noodles with Sesame Sauce') print(result[0]) #Mutton noodles '''The index that does not exist will report an error'''
5, Slice, (get multiple elements in tuple and get child tuple)
result = ('Mutton noodles', 'Haggis', 'Chinese hamburger', 'Pita Bread Soaked in Lamb Soup', 'Hengshan spicy sausage', 'Cold Noodles with Sesame Sauce') print(result[0:2]) #('mutton noodles',' sheep offal ')
6, Step size, (jump to get tuple content)
result = ('Mutton noodles', 'Haggis', 'Chinese hamburger', 'Pita Bread Soaked in Lamb Soup', 'Hengshan spicy sausage', 'Cold Noodles with Sesame Sauce') print(result[2::2]) #('roujiamo', 'Hengshan spicy sausage')
#Tuple inversion result = ('Mutton noodles', 'Haggis', 'Chinese hamburger', 'Pita Bread Soaked in Lamb Soup', 'Hengshan spicy sausage', 'Cold Noodles with Sesame Sauce') new = result[::-1] print(new) #('cold noodles',' Hengshan spicy sausage ',' mutton paomo ',' roujiamo ',' sheep offal ',' mutton noodles') #The original tuple cannot be modified. Only one tuple can be regenerated
7, for loop traversal tuple
result = ('Mutton noodles', 'Haggis', 'Chinese hamburger', 'Pita Bread Soaked in Lamb Soup', 'Hengshan spicy sausage', 'Cold Noodles with Sesame Sauce') for i in result: print(i) for i in range(len(result)): print(result[i])
set type
Unique function
1, Add element,. add(x)
date = {12,345,'asd',(99,)} print(date) #{'asd', 345, 12, (99,)}#The display is ordered, but it is disordered at the bottom of the computer date.add('520') print(date) #Add element x to the collection #{'asd', '520', 12, 345, (99,)}#Collections are mutable and can be added or deleted date.add(12) print(date) #{'asd', '520', 12, 345, (99,)}#Elements that already exist in the collection will not be added repeatedly
2, Delete element,. discard(x)
date = {12,345,'asd',(99,)} date.discard('asd') #Delete element x from the collection print(date) #{345, 12, (99,)}
3, Intersection,. intersection()
#Take the intersection of sets to generate a new set seta = {123,456,789} setb = {123,666,999} setc = seta.intersection(setb) #Find the intersection of set a and set b print(setc) #{123} print(seta & setb) #Operator intersection
4, Union,. union()
#Take the union of sets to generate a new set seta = {123,456,789} setb = {123,666,999} setd = seta.union(setb) #Find the union of set a and set b print(setd) #{789, 999, 456, 666, 123} print(seta | setb) #Operator Union
5, Difference set,. difference()
#Take the difference set of the set and generate a new set seta = {123,456,789} setb = {123,666,999} sete = seta.difference(setb) #Find the difference set between set a and set b print(sete) #{456, 789} print(seta - setb) #Operator difference set
Public function
1, Subtraction, (-)
#Operator difference set seta = {123,456,789} setb = {123,666,999} print(seta - setb) #{456, 789} print(setb - seta) #{666, 999} ''' Use set a Difference set b: aggregate a There are collections in b Element not in Use set b Difference set a: aggregate b There are collections in a Element not in '''
2, Intersection, and = (&)
#Operator intersection seta = {123,456,789} setb = {123,666,999} print(seta & setb) #{123}
3, Union, or = (|)
#Operator Union seta = {123,456,789} setb = {123,666,999} print(seta | setb) #{789, 999, 456, 666, 123}
4, Calculate the length, # get the number of collection elements,. len()
date = {12,345,'asd',(99,)} print(len(date)) #4
5, for loop set
date = {12,345,'asd',(99,)} for i in date: print(i) #The collection can only be looped through the for + variable; The collection cannot be cycled through the for+range index (because the collection is unordered)
dict type
Unique function
1, Get the value according to the key K. if the key does not exist, return None,. get(k)
Get the value according to the key K. if the key does not exist, return v, . get(k,v)
date = {'name':'helin', 'age':21, 'hobby':['soccer','swim'], ('1+1','=',2):True} print(date) ''' Multi line display is intuitive and concise Keys can only be hashable immutable types( str,int,bool,tuple),Cannot be a mutable type( list,set,dict) The value can be taken arbitrarily ''' result = date.get('name') #Returns the value corresponding to the key print(result) #helin result = date.get('clothes') #Nonexistent key, return None print(result) #None result = date.get('age','999') #Returns the value corresponding to the key print(result) #21 result = date.get('key','value') #Specifies a key that does not exist and returns v print(result) #value
#Case to realize user login user_set = { 'hll':'123', 'wby':'666' } user_name = input('Please enter user name:') user_pwd = input('Please input a password:') pwd = user_set.get(user_name)#Find the corresponding value in user_set according to the user_name entered by the user as the key #Simple logic comes first if not pwd: print('user name does not exist') else: if pwd == user_pwd: print('Login succeeded') else: print('Login failed')
2, Get all keys,. keys()
3, Get all values,. values()
4, Get all key values,. items()
date = {'name':'helin', 'age':21, 'hobby':['soccer','swim'], ('1+1','=',2):True} #print(date) result = date.keys() #Get all keys in the dictionary print(result) #dict_keys(['name', 'age', 'hobby', ('1+1', '=', 2)]) result = date.values() #Get all values of the dictionary print(result) #dict_values(['helin', 21, ['soccer', 'swim'], True]) result = date.items() #Get all the key values of the dictionary print(result) #dict_items([('name', 'helin'), ('age', 21), ('hobby', ['soccer', 'swim']), (('1+1', '=', 2), True)]) '''The key values are stored in a list of tuple packages'''
#for loop result = [('name', 'helin'), ('age', 21), ('hobby', ['soccer', 'swim']), (('1+1', '=', 2), True)] # Receive the element with a variable, and the index of the variable receives the element of the variable for item in result: print(item[0],item[1]) # The element that receives the element directly with two variables for key,value in result: print(key,value) #If the elements of the received variable and element are inconsistent, an error will be reported
## High imitation list dict_keys(), dict_values(), dict_items()
date = {'name':'helin', 'age':21, 'hobby':['soccer','swim'], ('1+1','=',2):True} #print(date) result = date.items() #Convert high imitation list to list print(list(result)) # [('name', 'helin'), ('age', 21), ('hobby', ['soccer', 'swim']), (('1+1', '=', 2), True)] #High imitation list for loop for i in result: print(i) # ('name', 'helin') # ('age', 21) # ('hobby', ['soccer', 'swim']) # (('1+1', '=', 2), True) #High imitation list operator in judgment if ('name', 'helin') in result: print(('name', 'helin')) else: print('non-existent') #('name', 'helin')
5, Set the value v according to the key K. if the key exists, no operation will be performed; if the key does not exist, new. setdefault(k,v) will be added
date = {'name':'helin', 'age':21, 'hobby':'soccer'} date.setdefault('hobby','swim') #Key exists, no operation print(date) #{'name': 'helin', 'age': 21, 'hobby': 'soccer'} date.setdefault('qq','123456789') #Key does not exist. Add this key value pair print(date) #{'name': 'helin', 'age': 21, 'hobby': 'soccer', 'qq': '123456789'}
6, Update key value pairs according to key k. if the key exists, it will be updated; if the key does not exist, it will be added,. undate({k:v})
date = {'name':'helin', 'age':21, 'hobby':'soccer'} date.update({'name':'hll','hobby':'soccer','qq':'123456789'})#() must be a dictionary, #Key exists, modify its value #Key does not exist. Add this key value pair print(date) #{'name': 'hll', 'age': 21, 'hobby': 'soccer', 'qq': '123456789'}
7, Remove the specified key value pair according to key K,. pop(k)
date = {'name':'helin', 'age':21, 'hobby':'soccer'} delete = date.pop('age') #Delete the key value pair in the original dictionary according to the key k, and assign the corresponding value to the variable according to the key print(date) #{'name': 'helin', 'hobby': 'soccer'} print(delete) #21 #If the key does not exist, an error will be reported
8, Remove in order (LIFO = stack),. popitem()
#Python 3.6 + is an ordered operation / Python 3.6 - the dictionary is unordered and deleted randomly (it can be changed into an ordered operation through the import module) date = {'name':'helin', 'age':21, 'hobby':'soccer'} delete = date.popitem() #Remove the last key value pair, and assign the removed key value pair to the variable in the form of tuple print(date) #{'name': 'helin', 'age': 21} print(delete) #('hobby', 'soccer')
Public function
1, Union set
#Python 3.9 only has the function of finding union to generate a new dictionary, the same key appears, and the back edge overwrites the value of the front edge dicta = {'aaa':111,'bbb':222,'ccc':333} dictb = {'aaa':123,'ppp':666,'ccc':333} dictc = dicta | dictb print(dictc) #{'aaa':123,'bbb':222,'ccc':333,'ppp':666}
2, Get the length, # get the number of dictionary key value pairs,. len()
date = {'name':'helin', 'age':21, 'hobby':'soccer'} print(len(date)) #3
3, The operator contains (in) \ (not in) to judge whether the element is in the container (dict,set,tuple,list/str).
date = {'name':'helin', 'age':21, 'hobby':'soccer'} judge = 'name' in date ##The default is the judgment of dictionary keys, which is equivalent to omitting. keys() print(judge) #True judge = 'name' in date.keys() print(judge) #True judge = 'helin' in date.values() print(judge) #True judge = ('name','helin') in date.items() print(judge) #True
4, Take the key as the index value,
date = {'name':'helin', 'age':21, 'hobby':'soccer'} print(date['name']) #Order is different from list and tuple. It takes value as index through key #helin '''If the key does not exist, an error will be reported (difference).get()(no error will be reported)'''
5, Add, modify and delete according to the key as the index
date = {'name':'helin', 'age':21, 'hobby':'soccer'} #Nonexistent key index, add directly date['qq'] = 123456789 print(date) #{'name': 'helin', 'age': 21, 'hobby': 'soccer', 'qq': 123456789} #The existing key index is the value of the modified key date['age'] = 20 print(date) #{'name': 'helin', 'age': 20, 'hobby': 'soccer', 'qq': 123456789} '''amount to.update(),Hard addition (difference).setdefault(),(soft add)''' #Delete the key value pair corresponding to the key del date['hobby'] print(date) #{'name': 'helin', 'age': 20, 'qq': 123456789} '''If the key does not exist, an error will be reported.pop(),(assignable)'''
6, for loop dictionary
date = {'name':'helin', 'age':21, 'hobby':'soccer'} for i in date: ##The default is the cycle of dictionary keys, which is equivalent to omitting. keys() print(i) for key in date.keys(): print(key) for value in date.values(): print(value) for key,value in date.items(): print(key,value)
None type
Only one value (None) indicates NULL; (NULL in other languages)
All None types in the definition point to an address. You don't have to generate a new address every time, so you can save memory.
There are no special unique and public functions;
#Convert None type to bool type print(bool(None)) #False
float type
Represents decimal; No unique features
pi = 3.1415926 e = 2.71828 #Convert floating point to integer print(int(pi)) #3 #Keep floating point to n decimal places print(round(e,3)) #2.718
Public function: addition, subtraction, multiplication and division
#Underlying storage principle a = 0.1 b = 0.2 print(a + b)#0.30000000000000004 print(round(a + b,1))#0.3 #An accurate calculation method for solving the above problems import decimal a = decimal.Decimal(str(a)) b = decimal.Decimal(str(b)) print(a + b)#0.3
Continuation:
Recommended learning videos:
Basic knowledge------ System teaching - Python 3.9 zero foundation introduction to mastery (full version)_ Beep beep beep_ bilibili
Data analysis------ [python tutorial] data analysis -- numpy, pandas, matplotlib_ Beep beep beep_ bilibili
Recommended Learning Websites:
n rookie tutorial------ Python 3 tutorial | rookie tutorial (runoob.com)
Basic sophomore------ Foundation_ Python sophomore CSDN blog
Recommended bloggers:
csdn/ WeChat official account ------python
Tiktok active ------python private tutor - butcher, programmer zhenguo(Python programming)
Leave your attention, collection and praise. Let me see who cares about me silently. Ha ha, thank you for browsing!