preface
What is a data type?
We humans can easily distinguish between numbers and characters, but computers can't. although computers are powerful, they are stupid from a certain point of view. Unless you clearly tell them that 1 is a Number and "Han" is a word, they can't distinguish between 1 and 'Han'. Therefore, there will be something called data type in every programming language, In fact, it is a clear division of various commonly used data types. If you want the computer to perform numerical operations, you pass numbers to it. If you want him to process words, you pass string types to him. Data types commonly used in Python include Number (int, float, complex, bool), string type (str), list type (list), set type (set), and dictionary type (dict).
1, Basic data types of python
Number type (number)
Integer (int)
On a 64 bit system, the number of bits of an integer is 64 bits, and the value range is - 263 ~ 263-1, i.e. - 9223372036854775808 ~ 9223372036854775807
For example:
Define an integer
intvar = 10 print(intvar) # result >>>>> 10
Use type to view the type of intvar
intvar = 10 print(type(intvar)) # result >>>>> <class 'int'>
Get memory address using id
print(id(intvar)) # result >>>>> 1962700080
Floating point
Floating point = decimal type
When the square is assigned as a variable, 15 decimal places are reserved by default and will not be rounded
floatvar = 10.15 print(floatvar,type(floatvar)) # result >>>>> 10.15 <class 'float'> floatvar = 10.1555513312432155 print(floatvar,type(floatvar)) # result >>>>> 10.155551331243215 <class 'float'>
When float is used in the formatted output of a variable and% - string is used for formatting, the default is 6 decimal places
a = float(6) print('%f'%(a)) # result >>>>> 6.000000
Of course, you can also customize the reserved digits
. 2f is equivalent to retaining 2 decimal places
a = float(6) print('%.2f'%(a)) # result >>>>> 6.00
For other operations or formatted output, the default is one decimal place. If there are more digits, the maximum digit is taken
a = float(6) b = float(3) c =a+b print(c) # result >>>>> 9.21 a = float(6) b = float(3) print("{},{}".format(a,b)) # result >>>>> 6.0,3.0
In addition, format has the function of rounding. You can try it yourself
complex
complex real + imaginary
1+2j
1: Real number
2j: imaginary number
j: If there is a number whose square is equal to - 1, then this number is j, which expresses a high-precision type
complexvar = 1-2j print(complexvar) print(type(complexvar)) # result # (1-2j) # <class 'complex'> complexvar = -2j print(complexvar) print(type(complexvar)) # result # (-0-2j) # <class 'complex'>
Boolean type (bool)
Boolean type has only two values: True, False and False. It is generally used in judgment or loop
boolvar = True boolvar = False print(boolvar) print(type(boolvar))
Mathematical function
abs(x) Returns the absolute value of a number, such as abs(-10) Return 10 ceil(x) Returns the ascending integer of a number, such as math.ceil(4.1) Return 5 cmp(x, y)If x < y return -1, If x == y Return 0, If x > y Return to 1. Python 3 Obsolete. Use use (x>y)-(x<y) Replace. exp(x) return e of x pow (ex),as math.exp(1) Return 2.718281828459045 fabs(x) Returns the absolute value of a number, such as math.fabs(-10) Return 10.0 floor(x) Returns the rounded down integer of a number, such as math.floor(4.9)Return 4 log(x) as math.log(math.e)Return 1.0,math.log(100,10)Return 2.0 log10(x) Returns a value based on 10 x Logarithm of, e.g math.log10(100)Return 2.0 max(x1, x2,...) Returns the maximum value of a given parameter, which can be a sequence. min(x1, x2,...) Returns the minimum value of a given parameter, which can be a sequence. modf(x) return x The integer part and decimal part of, the numerical symbols of the two parts and x Similarly, the integer part is represented as a floating point. pow(x, y) x**y Calculated value. round(x [,n]) Returns a floating point number x The rounded value of, as given n Value, represents the number of digits rounded to the decimal point. sqrt(x) Return number x The number can be negative and the return type is real, such as math.sqrt(4)Return 2+0j
trigonometric function
acos(x) return x Arccosine radian value of. asin(x) return x Arcsine radian value of. atan(x) return x Arctangent radian value of. atan2(y, x) Returns the given X and Y The arctangent of the coordinate value. cos(x) return x Cosine of the radian of. hypot(x, y) Returns the Euclidean norm sqrt(x*x + y*y). sin(x) Returned x The sine of the radian. tan(x) return x Tangent of radian. degrees(x) Convert radians to angles,as degrees(math.pi/2) , Return to 90.0 radians(x) Convert angles to radians
Mathematical Constants
pi Mathematical Constants pi(PI, generally expressed inπ(to represent) e Mathematical Constants e,e That is, the natural constant (natural constant).
Small data pool
id => id Is the memory address is => Compare whether the memory on both sides is equal == => Compare whether the values on both sides are equal = => Is assignment
Cache mechanism of small data pool
Small data pool, also known as small integer caching mechanism, or resident mechanism, etc, For numbers: -5~256 It will be added to the small data pool. Each use is the same object. For strings: 1.If the length of the string is 0 or 1, Will be cached by default 2.String length greater than 1, But the string contains only letters, number, Cache only when underline 3.The multiplied string multiplier is 1, Contains only numbers,letter,Underscores are cached. If Contains other characters, And length<=1 Will also be resident,Multiplier greater than 1 . Contains only numbers, letter, Down stroke The line will be cached at this time. However, the string length cannot be greater than 20 4.Designated resident. We can pass sys In the module intern()Function to specify what to host.
String type (str '' or '')
concept
Definition: use '', '', '' or ''. The part contained in the middle is called a string
PS: even if a number is written in it, its data type is also a string
characteristic:
1. The character set is defined from left to right, and the subscripts are accessed sequentially from 0
2. Slicing operation can be performed
3. Immutable. The string is immutable. You cannot modify an element like a list. All modification operations on the string are actually equivalent to generating a new data.
Supplement:
1. The single quotation mark and double quotation mark of the string cannot cancel the meaning of special characters. If you want all characters in the quotation mark to cancel the special meaning, add r before the quotation mark, such as name = r'l\thf '
String usage
# Single quoted string a = '11111' # Double quoted string b = "abc" print(a,b,type(a),type(b)) # result >>>>> 11111 abc <class 'str'> <class 'str'>
String with three quotation marks, supporting cross line effect
strvar = """ Look at the sword with a lamp in the drunk, Dream back to the camp. Under the command of 800 Li Fen, Fifty strings turn over the Great Wall, Autumn soldiers on the battlefield. """ print(strvar,type(strvar)) # result >>>>> Look at the sword with a lamp in the drunk, Dream back to the camp. Under the command of 800 Li Fen, Fifty strings turn over the Great Wall, Autumn soldiers on the battlefield. <class 'str'>
Escape character
\+ a character
(1) Make meaningful characters meaningless
(2) Make meaningless characters meaningful
\N and \ r\n: Wrap
\T: tab indent (horizontal tab) (generally, a lock is a distance of 4 spaces)
\r: pull the following characters directly to the beginning of the current line
Meta string
r "string" does not escape characters and prototypes the output string
strvar = r"E:\npython31\tay2" print(strvar) # result >>>>> E:\npython31\tay2 <class 'str'>
format string
Syntax: "string"% (value 1, value 2, value 3)
%d integer placeholder
%2d occupies two digits, and the original string is on the right by default
strvar = "I this year%2d year" % (2) print(strvar) # result >>>>> I'm 2 years old
%-2d occupies two digits, and the original string is left by default (generally useless)
strvar = "White star princess this year%-2d year" % (200) print(strvar)
%Placeholder f
%. 2f keep 2 decimal places
%f there is rounding
strvar = "%.2f" % (2.566) print(strvar) # result >>>>> 2.57
%s string placeholder
a = "Saturday" b = "Sunday" c = 12 d = 1.5 e = 3.1415926 strvar = "Today is%s,Tomorrow is%s,%d,%f,%.2f" % (a,b,c,d,e) print(strvar) # result >>>>> Today is Saturday, tomorrow is Sunday, 12,1.500000,3.14
Format string using format
# 1. Transfer parameters in sequence strvar = "{}Like to eat{}".format("I","Apple") print(strvar) # 2. Index transfer parameter strvar = "{1}Like to eat{0}".format("Apple","I") print(strvar) # 3. Keyword transfer parameter strvar = "{thing2}Like to eat{thing1}".format(thing1="Apple",thing2="I") print(strvar) # 4. Container type data (list or tuple parameter) strvar = "{0[2]}Like to eat{1[1]}".format(["Xiao Hong","Xiao Ming","Xiao Gang"],("Apple","Banana","pineapple")) print(strvar) # In format, reverse subscripts cannot be used and are not recognized # strvar = "{0[-1]} likes to eat {1 [- 1]}" Format (["Xiaohong", "Xiaoming", "Xiaogang"], ("apple", "banana", "pineapple") # print(strvar) # If the container is a dictionary strvar="{group1[xiaoming]}Like to eat{group2[0]}".format(group1={"xiaohong":"Xiao Hong","xiaoming":"Xiao Ming"},group2=("Banana","Apple")) print(strvar)
Use of format padding symbols and conversion to special symbols
# Use of padding symbols for format (^ < >) """ ^ Center original string < Original string left > Original right string {who:*^10} who:Keyword parameters *:Characters to fill ^:Center original string 10:Total length=Original string length+Fill character length """ strvar = "{who:*^10}stay{where:>>10}eat{what:!<10}".format(who="I",where="Other people's house",what="Apple") print(strvar) # Use of hexadecimal conversion to special symbols (: D: F: s:) # : d integer placeholder requires that the type must be an integer strvar = "I've eaten{:d}An apple".format(3) #3.5 error # : 2d occupies two digits. If it is not enough to fill in the blank, it is on the right by default strvar = "I've eaten{:2d}An apple".format(3) # < > ^ adjust the corresponding position strvar = "I've eaten{:<2d}An apple".format(3) strvar = "I've eaten{:<3d}An apple".format(3) print(strvar) # : f floating point placeholder (required type must be floating point) strvar = "My grades are{:f}".format(96.25) # . 2f keep two decimal places strvar = "My grades are{:.2f}".format(96.25) print(strvar) # : s string placeholder (required type must be string) strvar = "{:s}".format("Lala Lala") print(strvar) # : money placeholder strvar = "{:,}".format(3256224583) print(strvar) # Comprehensive case strvar = "I this year{:d}year,My Chinese score is{:.1f},My mood{:s}".format(23,98.65,"very nice") print(strvar)
String related operations
1. String splicing
strvar = 'abc' + 'def' print(strvar) # Output: abcdef
2. Duplicate string
strvar = 'qwer' * 3 print(strvar) # Output: qwerqwerqwer
3. Cross line splicing of strings
strvar = 'qwer' \ 'ert' print(strvar) # Output: qwerert
4. Index of string
Forward index 0123 strvar = "1234" Reverse index -4-3-2-1
5. Slicing of strings
Note: [start index: end index: interval value]
res = strvar[::2] # 0 2 4 6 8... Intercept from start to end
res = strvar[::-1] # -1 -2 -3 -4 -5 -6... Intercept from end to front
# [start index:] intercept from the start index to the end of the string strvar="Red orange yellow green cyan purple" res = strvar[4:] print(res) # [: end index] intercept from the beginning to before the end index (end index - 1) res = strvar[:5] print(res) # [start index: end index] intercept from the start index to before the end index (end index - 1) res = strvar[1:3] print(res) # [start index: end index: interval value] intercept characters at a specified interval from the start index to the end index # positive sequence res = strvar[::2] # 0 2 4 6 8..... Intercept from beginning to end print(res) # Reverse order res = strvar[::-1] # -1 -2 -3 -4 -5 -6..... print(res) # [:] or [::] intercept all strings res1 = strvar[:] res2 = strvar[::] print(res1) print(res2)
String correlation function
General:
# Capitalize string initial strvar ="what is your name" res = strvar.capitalize() print(res) # What is your name # title capitalize the first letter of each word strvar ="what is your name" res = strvar.title() print(res) # What Is Your Name # upper capitalizes all letters strvar ="what is your name" res = strvar.upper() print(res) # WHAT IS YOUR NAME # lower makes all letters lowercase strvar = "HELLO KITTY" res = strvar.lower() print(res) # hello kitty # Swap case case case interchange strvar = "AAAAbbbb" res = strvar.lower() print(res) # aaaaBBBB # len calculates the length of the string strvar = "AAAAbbbb" res = len(strvar) print(res) # 8 # count counts the number of an element in a string strvar = "AAAAbbbb" res = strvar.count("A") print(res) # 4 # find finds the index position of the first occurrence of a string (recommended) '''character string.find("character",Start indexing,End index) If not found, return directly-1''' strvar = "abcdefabc" res = strvar.find("a") # 0 res = strvar.find("a",2) # 6 res = strvar.find("d",2,5) # 3. The end index itself cannot be retrieved. The previous value is retrieved print(res) # The function of index is the same as that of find. If find cannot find the data, it returns - 1. If index cannot find the data, it will report an error res = strvar.index("d",6,8) # error # Startswitch determines whether to start with a character or string ''' character string.startswith("character string",Start indexing,End index) Return if present True,Otherwise return False ''' strvar = "abcdefg" res = strvar.startswith("a") # True res = strvar.startswith("b",1) # True res = strvar.startswith("c",2,5) # True 2 3 4 print(res) # Endswitch determines whether it ends with a character or string res = strvar.endswith("g") # True res = strvar.endswith("g",-6) # True res = strvar.endswith("d",-6,-3) # True print(res)
is judgment class
# isupper determines whether all strings are uppercase letters strvar = "ABCD" res = strvar.isupper() print(res) # True # islower determines whether all strings are lowercase letters strvar = "abcd123" res = strvar.isupper() print(res) # True # isdecimal detects whether a string is composed of numbers. It must be pure numbers strvar = "12345" strvar = "123.4567" res = strvar.isdecimal() print(res)
Fill / remove
strvar = "abc" # ljust fills in the string, and the original character is left (fill in spaces by default) res = strvar.ljust(10) print(res) # rjust fills in the string, with the original character to the right (fill in spaces by default) res = strvar.rjust(10) print(res) # center fills the string, and the original character is centered (blank is filled by default) res = strvar.center(10) # Original string length + filled character length = 10, filled with spaces by default res = strvar.center(10,"#") print(res) # strip removes the blank characters on both sides of the beginning and end by default strvar = "####abcd####" res = strvar.strip("#") # Specifies the symbol to remove print(res) # rstrip removes a character on the right print(strvar.rstrip("#")) # rstrip removes a character on the left print(strvar.lstrip("#"))
Three common methods of string (important)
# split splits a string into a list by character (the default character is a space) strvar = "one two three four" lst = strvar.split() strvar= "one-two-three-four" lst = strvar.split("-") # Separate from left to right lst = strvar.rsplit("-",2) # From right to left, you can specify the number of times to separate print(lst) # join concatenates a list into a string by a character lst = ['five','six','seven','eight'] res = "-".join(lst) print(res) # replace replaces the old character of the string with the new character '''replace(Character to replace,Replace with what,Number of replacements)''' strvar = "This little dog is so cute, really, really cute" res = strvar.replace("lovely","Interesting") res = strvar.replace("lovely","Interesting",1) # Replace only once print(res)
List type (list [])
concept
List is one of the basic data types in python. Other languages also have data types similar to list. For example, it is called array in js. It is enclosed by [] and each element is separated by commas. It can store various data types, such as
Definition: [] is separated by commas, and various data types are stored according to the index. Each position represents an element
characteristic:
1. Multiple values can be stored
2. List elements are defined from left to right, and subscripts are accessed from 0 in order
3. The value corresponding to the specified index position can be modified, which is variable
li = ['alex',123,True,(1,2,3,'wusir'),[1,2,3,'Xiao Ming',],{'name':'alex'}]
Compared with strings, lists can store not only different data types, but also a large amount of data. The limit of 32-bit python is 536870912 elements, and the limit of 64 bit python is 1152921504606846975 elements. Moreover, the list is orderly, has index values, can be sliced, and is convenient to take values.
List operation
# 1. List splicing (same tuple) lst1 = [1,2,3] lst2 = [4,5,6,7,8,8] res = lst1 + lst2 print(res) # 2. Repetition of list (same tuple) res = lst1 * 6 print(res) # 3. Slicing of list (same tuple) # Syntax: list [::] full format: [start index: end index: interval value] # (1) [start index:] intercept from the start index to the end of the list # (2) [: end index] intercept from the beginning to before the end index (end index - 1) # (3) [start index: end index] intercept from the start index to before the end index (end index - 1) # (4) [start index: end index: interval value] intercept the list element value at the specified interval from the start index to the end index # (5) [:] or [::] intercept all lists lst=["Alan","Cat","Sun","Wuming","Huahai","Mc","Orange","Rxy"] # (1) [start index:] intercept from the start index to the end of the list res = lst[3:] print(res) # (2) [: end index] intercept from the beginning to before the end index (end index - 1) res = lst[:6] print(res) # (3) [start index: end index] intercept from the start index to before the end index (end index - 1) res = lst[3:6] print(res) # (4) [start index: end index: interval value] intercept the list element value at the specified interval from the start index to the end index # Forward interception res = lst[::2] print(res) # Reverse interception res = lst[::-2] print(res) # (5) [:] or [::] intercept all lists res = lst[:] res = lst[::] print(res) # 4. Acquisition of list (same tuple) # 0 1 2 3 4 5 6 7 lst=["Alan","Cat","Sun","Wuming","Huahai","Mc","Orange","Rxy"] # -8 -7 -6 -5 -4 -3 -2 -1 res = lst[6] res = lst[-2] print(res) # 5. Modification of list (slicable) ''' The required data type is:Iterative data(Container type data,range object,iterator ) ''' lst=["Alan","Cat","Sun","Wuming","Huahai","Mc","Orange","Rxy"] # Using slicing, you can modify multiple elements at a time, without any limit on the number lst[1:3] = "abcdef" print(lst) # Slice matching step, how many elements are cut out and how many elements are modified lst=["Alan","Cat","Sun","Wuming","Huahai","Mc","Orange","Rxy"] res = lst[::2] # Alan Sun Huahai Orange lst[::2] = range(1,5) print(lst) # 6. Deletion of list lst=["Alan","Cat","Sun","Wuming","Huahai","Mc","Orange","Rxy"] del lst[-1] print(lst) # The variable res itself is deleted, not the elements in the list ''' res = lst[-1] del res print(lst) ''' # del lst[:2] del lst[::3] #0 3 6 9 12... print(lst) # A list in a tuple in which elements can be modified; tup = (1,2,3,[4,5,6,(7,8,9)]) tup[-1][1] = 66 print(tup)
List related functions (addition, deletion and other functions)
increase
Add append insert extend (key)
# append adds a new element to the end of the list li = [6,8,7,5,8] li.append(2) # Append at the end, the original value is appended later, so there is no need to assign a new value print(li) # insert appends to the specified index location li = [6,8,7,5,8] li.insert(2,"b") # The preceding parameter specifies the index, separated by commas, plus the element to be inserted print(li) # extend extends the original list. The parameters can be iterated objects (numbers cannot be extended and numbers cannot be iterated) li = [6,8,7,5,8] li.extend("b") # Extended append. print(li)
Delete
Delete pop remove clear (key)
# pop deletes a value through the index. If there is no index, the last value will be deleted by default. You can also get the deleted value by giving a value li = [6,8,7,5,8] v = li.pop(2) # Specify index deletion. If there is no index, the last value will be deleted by default. You can also get the deleted value print(li) print(v) # remove deletes the specified value in the list, and the left takes precedence li = [6,8,7,5,8] li.remove(8) # Delete the value specified in the list, and take precedence from the left print(li) # Clear clear list li = [6,8,7,5,8] li.clear() # clear list print(li)
Other functions
Other functions index count sort reverse
lst=["Fly","Fly","Fly","Fly","Hurt","Cat","Alan","Yang"] # Index gets the index of a value in the list '''list.index(value,[,start],[,end]) An error is reported when the optional expression parameter is not found''' res = lst.index("Hurt") res = lst.index("Hurt",3) res = lst.index("Hurt",2,4) print(res) # count counts the number of occurrences of an element res = lst.count("Fly") print(res) ''' Note: in the string count You can delimit the scope, which is in the list count no way ''' strvar = "aaaaabcdefg" res = strvar.count("a",1,6) print(res) # sort() list sort (default small to large sort) # Default from small to large lst=[3,8,26,9,-25,-1,7] lst.sort() # Sort from small to large lst.sort(reverse=True) print(lst) # Sort English ---- -- > ASCII encoding '''Compare one by one, compare the second in the same case for the first time, and so on''' lst=["Cow","Fly","Hurt","Cat","Alan","Yang"] lst.sort() print(lst) # You can also sort Chinese ---- > but there are no rules to follow lst = ["Wang Tianlong","Chen Zhengzheng","Xia Shengqin","Wan Xiaoyang","Peng Yunfei"] lst.sort() print(lst) # reverse() list inversion operation lst = ["Wang Tianlong","Chen Zhengzheng","Xia Shengqin","Wan Xiaoyang","Peng Yunfei"] lst.reverse() print(lst)
Deep and shallow copy
concept
copy Shallow copy, without copying sub objects, so if the original data changes, the sub objects will change Deep copy includes the copy from the object in the object, so the change of the original object will not cause the change of any child elements of deep copy berry
Shallow copy
# 1. Light copy import copy lst1=[1,2,3] # Method 1: copy Copy module method lst2 = copy.copy(lst1) lst1.append(4) print(lst1) #[1, 2, 3, 4] print(lst2) #[1, 2, 3] # Method 2: list copy() lst1 = [1,2,3,4] lst3 = lst1.copy() lst1.insert(0,0) print(lst1) # [0, 1, 2, 3, 4] print(lst3) # [1, 2, 3, 4]
Deep copy
# Introduce deep copy (shallow copy cannot meet requirements) lst1 = [1,2,3,[4,5,6]] lst2 = copy.copy(lst1) lst1[-1].append(7) lst1.append(100) print(lst1) # [1, 2, 3, [4, 5, 6, 7], 100] print(lst2) # [1, 2, 3, [4, 5, 6, 7]] # Deep copy import copy lst3 = [1,2,3,[4,5,6]] lst4 = copy.deepcopy(lst3) lst4[-1].append(0) print(lst4) # [1, 2, 3, [4, 5, 6, 0]] print(lst3) # [1, 2, 3, [4, 5, 6]] print(id(lst2[-1])) # 2731177062472 print(id(lst1[-1])) # 2731177036872 print(id(lst1[0])) # 1347321968 print(id(lst2[0])) # 1347321968 lst2[0] = 11 print(id(lst1[0])) # 1347321968 print(id(lst2[0])) # 2390383439568
Summary of deep and shallow copies
1.Shallow copy copies only all data in the primary container 2.Deep copy copies all elements at all levels Shallow copies are faster than deep copies Deep copy at execution time: If it is immutable data,The address will temporarily point to the original data, In case of variable data,Directly open up new space Immutable data: Number str tuple Variable data : list set dict
Tuple type (tupe())
concept
Tuples are the secondary processing of lists. The writing format is parentheses (). The elements in which tuples are placed cannot be modified, and the elements in tuples cannot be added or deleted. Therefore, tuples are also called read-only lists and cannot be modified. It can only be modified under specific circumstances
Definition: similar to the list, except that [] is changed to ()
characteristic:
1. Multiple values can be stored
2. Immutable
3. Tuple elements are defined from left to right, and subscripts are accessed sequentially from 0
Common operations of tuples
Index slice
tu = (1,2,'alex','oldboy') #section print(tu[:2]) #Specify index value print(tu[2])
Traversal tuple
tu = (1,2,'alex','oldboy') for i in tu: print(i)
Note: the tuple itself is immutable. If the tuple also contains other variable elements, these variable elements can be changed
tu = (1,2,'alex',[1,'taibai'],'oldboy') tu[3].append('yuhuang') print(tu)
The above code is because the tuple only stores the memory address of each element, [1 'taibai'] the memory address of the list itself does not change in the tuple, but the memory address of the elements contained in the list exists in another space and is variable.
Tuple operator
Like strings, tuples can be manipulated with + and * signs. This means that they can be combined and copied, and a new tuple will be generated after the operation.
For example:
print(len((1, 2, 3,))) The result is 3 (1, 2, 3) + (4, 5, 6) The result is (1, 2, 3, 4, 5, 6) ('Hi!',) * 4 The result is ('Hi!', 'Hi!', 'Hi!', 'Hi!') 3 in (1, 2, 3) The result is True for x in (1, 2, 3): print(x) The result is 1 2 3
Tuple related methods
len(tuple) Calculate the number of Yuanzu max(tuple) Returns the maximum value of element in Yuanzu min(tuple) Returns the minimum value of the element in the ancestor tuple(seq) Convert ancestor list to
Dictionary type (dict {})
concept
Definition: {key1:value1,key2:value2} (Syntax)
1. Keys and values are separated by a colon ":;
2. Items are separated from each other by commas ",";
Example:
dic = { 'name':'Li Si', 'age':17, 'name_list':['Zhang San','Li Si'], } print(dic['name']) # Output: Li Si print(dic['name_list']) # Output: ['Zhang San', 'Li Si']
characteristic:
1. Key value structure
2. The key must be an immutable data type and unique
3. Any number of value s can be stored, modifiable and not unique
4. Disorder
5. The query speed is fast and is not affected by the size of dict
Supplement:
Dictionary is the only mapping type in python. It stores data in the form of key value pairs.
Store a large amount of data, which is relational data, and query data quickly.
The list is traversed from beginning to end
Dictionary use binary search
Binary Search, also known as Binary Search, is an efficient search method.
For example, the dictionary has 1 ~ 100 data. Now you want to find 75.
Split it in half and find the middle value of 50. Judge the size of 50 and 75, find that it is less than, and then split it in half.
Find the middle value of 75 and return the result directly.
For string lookup
Each string has a hash value, which is unique.
print(hash('a')) # Output: 977260134378667761 print(hash('afdsfeye')) # Output: 6608581710363481317
Dictionary related methods
Increase (fromkeys)
# dic [key] = value dic={} dic["Top"] = "Fly" dic["Mid"] = "Mojo" dic["Support"] = "Snow" print(dic) # Output: {top ':'fly', 'mid':'mojo ',' support ':'snow'} # fromkeys() creates a dictionary with a set of keys and default values lst=["Top","Jungle","Bottom"] dic={}.fromkeys(lst,None) print(dic) # Output: {top ': none,' jungle ': none,' bottom ': none} # Note: the three keys point to the same list (not recommended) '''dic = {}.fromkeys(lst,[])'''
pop popitem clear
# pop() deletes the key value pair with the key (if there is no such key, the default value can be set to prevent error reporting) dic={"Top":"Fly","Bottom":"Hurt","Jungle":"Giao","Mid":"Mojo","Support":"Snow"} res = dic.pop("Top") # 1. If a nonexistent key is deleted, an error will be reported directly res = dic.pop("King") # 2. You can set the default value to prevent error reporting res = dic.pop("King","Without this key") print(res) # popitem() deletes the last key value pair res = dic.popitem() print(res,dic) # clear() clear dictionary dic.clear() print(dic)
update
# update() batch update (update with this key and add without this key) dic1={"Top":"Fly","Bottom":"Hurt","Jungle":"Giao"} dic2={"Top":"JieJ","Support":"770","Jungle":"Giao"} # Method 1 (recommended) dic1.update(dic2) print(dic1) # Method 2 dic1.update(coach="SK",teacher="Bao") print(dic1)
get
#get() obtains the value through the key (if there is no such key, the default value can be set to prevent error reporting) dic={"Top":"Fly","Bottom":"Hurt","Jungle":"Giao"} res = dic.get("Top") res = dic.get("Coach") res = dic.get("Coach","Without this key") print(res)
Other functions (keys values items) are important
dic={"Top":"Fly","Bottom":"Hurt","Jungle":"Giao"} #keys() combines the dictionary keys into a new iteratable object res = dic.keys() print(res) #values() combines the values in the dictionary into a new iteratable object res = dic.values() print(res) #items() gathers the key value pairs of the dictionary into tuples to form a new iteratable object res = dic.items() print(res)
Set type (set {})
concept
definition
Collection is a bit like the list we learned. It can store a pile of data, but it has several unique features that make it occupy a place in the whole Python language,
1. The immutable elements mean that you can't save a list or dict in the set. Immutable types such as string, number and tuple can be saved
2. It is natural to lose weight. There is no way to store duplicate elements in the set
3. Unordered. Unlike the list, the position in the list is marked by index. The elements are unordered. The elements in the set have no order. For example, the sets {3,4,5} and {3,5,4} are counted as the same set
Collection related operations
Basic data type features (variable: list, dictionary, immutable: string, number, tuple)
The elements in the collection must be immutable types. Adding variable types will report an error
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'} print(student) # Output set, duplicate elements are automatically removed # Member test if('Rose' in student) : print('Rose In collection') else : print('Rose Not in collection')
Set operation (important)
set1={"Chuchen","Yinuo","JiuC","Cat"} set2={"15sui","SK","Dgc","Cat"} # Intersection abbreviation& res = sey1 & set2 print(res) # Difference set abbreviation- res = set1 - set2 print(res) # Union abbreviation| res = set1 | set2 print(res) # Abbreviation of symmetric difference set^ res = set1 ^ set2 print(res) # Determine whether it is a subset abbreviation< res = set1 < set2 print(res) # Determine whether it is a parent set abbreviation > res = set1 > set2 print(res)
Correlation function of set
add update
# add, adding variable data types will also report errors s = {1,2,5,5,'g','h'} s.add(3) print(s) # update() iteratively increases (one heap at a time) strvar = ("Ache","Yuyu") setvar.update(strvar) print(setvar)
clear pop remove discard
set2 = {"Fly","JieJ","Rxy"} # clear() clear the collection set2.clear() # pop() randomly deletes a data in the collection res = set2.pop() print(res,set2) # remove() deletes the specified value in the collection (an error will be reported if it does not exist) (understand) setvar.remove("Fly") print(setvar) # discard() deletes the value specified in the collection (if it does not exist, it will not be deleted) (recommended) set2.discard("Fly") set2.discard("Sehah") print(set2)
other
set1={"Chuchen","Yinuo","JiuC","Cat"} set2={"15sui","SK","Dgc","Cat"} # Intersection res = set1.intersaction(set2) print(res) #difference() difference set res = set1.difference(set2) print(res) #union() Union res = set1.union(set2) print(res) #symmetric_difference() symmetric difference set (the complement case is included) res = set1.symmetric_difference(set2) print(res) #issubset() determines whether it is a subset set1 = {"Fly","JieJ","Nuoyan","Orange"} set2 = {"Fly","JieJ"} res = set1.issubset(set2) #issuperset() determines whether it is a parent set res = set1.issuperset(set2) print(res) #isdisjoint() detects whether two sets do not intersect. Disjoint is True and intersection is False res = set1.isdisjoint(set2) print(res)
Frozen collection
Frozen set / fixed set: a set that cannot be modified once created. A data type. If a set is compared to a list, a frozen set is a tuple.
Function of freezing collection:
Provide an unchangeable cross reference set for the operation of the set.
Frozen sets are the same as sets except that they cannot be modified!
copy() have access to difference() Difference sets can be used difference_update() Update difference set is not available intersection() Intersection can be used intersection_update()Update intersection is not available union() Union can be used update()Update union is not available issuperset() Detection supersets can be used issubset() Detection subsets can be used isdisjoint() Detect whether disjoint can be used symmetric_difference()You can use (symmetric difference set) symmetric_difference_update()Not available (update symmetric difference set)
# frozenset can force the container type data to become a frozen collection lst1 = ["Fly","Mojo","Hurt","770"] fz1 = frozenset(lst1) lst2 = ("Amy","Mike","Lucy") fz2 = frozenset(lst2) print(fz1 , type(fz1)) print(fz2 , type(fz2)) # You cannot add or remove elements from a frozen collection fz1.add("Marry") # error # You can only make up the difference print(fz1 & fz2) print(fz1 - fz2)
Cast and automatic type conversion
Number type cast (int, float, bool, complex)
Integer int
float Can be converted into int bool Can be converted into int str(Shape such as"123")Can be converted into int complex Cannot be converted into int str(Shape such as"abc123")Cannot be converted into int
Floating point float
int Can be converted into float bool Can be converted into float str(Shape such as"123")Can be converted into float
Boolean bool
bool There are ten cases where the type is false: 0, 0.0, False, 0j, '', [], {}, (), set(), None None yes python Keywords for,Represents empty,nothing in the world,Generally used for initialization
Complex complex
int Can be converted into complex float Can be converted into complex bool Can be converted into complex str(Shape such as"123")Can be converted into complex str(Shape such as"abc123")Cannot be converted into complex
Number automatic type conversion
Conversion of accuracy from low to high : bool -> int -> float -> complex Automatic type conversion,The default is to convert from low precision to high precision(From low to high) The following automatic type conversions can be implemented: 1.bool+int 2.bool+float 3.bool+complex 4.int+float 5.int+complex 6.float+complex
Cast of container type (str, list, tuple, set, dict)
String type str
All containers and Number,str Can be cast successfully Strong to string,It is nothing more than putting quotation marks on both sides on the basis of the original data repr()Function: you can prototype the output string,Non escape character(Show quotation marks)
List type list
1.If string,Each character is placed in the list as an element 2.If it's a dictionary,Keep keys only,Form a new set of lists 3.If it's another container,Just simply replace it on the basis of the original data[]
Tuple type tuple
1.If string,Each character is placed as an element in the tuple 2.If it's a dictionary,Keep keys only,Form a new set of tuples 3.If it's another container,Just simply replace it on the basis of the original data()
Set type set
1.If string,Each character is put into the collection as an element(disorder,Automatic weight removal) 2.If it's a dictionary,Key retention only,Form a new set 3.If it's another container,Just simply replace it on the basis of the original data{}
Dictionary type dict
1. Secondary container: including secondary list, secondary tuple, secondary set and secondary dictionary.
2. Multi level container: for containers of 3.4.5.6 or higher level, the values obtained are as follows.
# Five stage container container = [10,20,(1,2,3,{"a":1,"b":{"c":2,"d":[3,4,"success "]}})] # Get success res1 = container[-1] print(res1) # (1,2,3,,{"a":1,"b":{"c":2,"d":[3,4,"success "]}} res2 = res1[-1] print(res2) # {"a":1,"b":{"c":2,"d":[3,4,"success "]}} res3 = res2["b"] print(res3) # {"c":2,"d":[3,4,"success "]} res4 = res3["d"] print(res4) # [3,4,"success "] res5 = res4[-1] print(res5) # success # Five step synthesis one step res = container[-1][-1]["b"]["d"][-1] print(res) # success
3. Equal length secondary containers: all elements in the container are containers, and the number of elements in the container is the same, as follows:
lst = [(1,2,3) , [4,5,6]] lst = [(1,2) , [3,4]]
4. Forced conversion of dict to Dictionary: when forced conversion to dictionary, it must be a secondary container with equal length, and the number of elements in it is 2, as follows:
1.The outer layer is a list or tuple or collection,The containers inside are tuples or lists(recommend) lst = [("a",1),["b",2]] tup = (("c",3),["d",4],) setvar = {(1,2),(3,4),("a1",3),("b2",4)} res = dict(lst) # {'a': 1, 'b': 2} res = dict(tup) # {'c': 3, 'd': 4} print(res) 2.If it's a collection,Syntactically allowed,But there are limitations(Not recommended) lst = [{"a",1},{"b",2}] # Because the collection is out of order and does not meet the original intention of the definition, it is not recommended print(dict(lst)) 3.If a string is used,Syntactically allowed,But there are limitations(Not recommended) lst = [("a",1),"a2"] # String length can only be 2 lst = [("a",1),"a123"] error print(dict(lst))
Summary of container types
String (str)
The string type is indexed, ordered, available, unmodifiable, and hash able
list
The list type is indexed, ordered, obtainable, modifiable, and non hash
Tuple (tupe)
Tuple types are indexed, ordered, obtainable, unmodifiable, and hash able
Dictionary (dict)
Dictionary types have key value pairs (obtained by keys). They appear to be orderly, but actually they are disordered. They can be obtained, modified and hash ed
set
The collection type is indexed, unordered, unavailable, modifiable, and hash able
Garbage collection mechanism
concept
one. Python Internal use of reference counting mechanism, To keep track of objects in memory,All objects have reference counts. Assign a new name to an object, Then put it into a container(Such as list, Yuanzu, Dictionaries), So the count increases. When we use delect Delete statement to delete an object alias or, The reference exceeds this scope,Or when it is copied again,The count of references decreases.For immutable data(number,character string)The interpreter shares memory in different parts of the program, To save memory.sys.getrefcount( )Function to get the current reference count of the object two. What about the garbage collection mechanism, Is when the reference count of an object returns to zero,He will be disposed of by the garbage collection mechanism ,When two objects refer to each other, del Statement can reduce the number of references and destroy the name of the underlying object, Because each object contains a reference to other objects, Therefore, the reference count does not return to zero, Objects are not destroyed,To solve this problem, the interpreter periodically executes a loop detector to search for loops of inaccessible objects and delete them. three.Memory pool mechanism Python Provides a garbage collection mechanism for memory, but it places unused memory in the memory pool instead of returning it to the operating system. 1,Pymalloc Mechanism. To accelerate Python Efficiency of implementation, Python A memory pool mechanism is introduced to manage the application and release of small memory. 2,Python All objects less than 256 bytes in the are used pymalloc Implemented allocators, while large objects use the system's malloc. 3,about Python Objects such as integers, floating point numbers, and List,Each has its own private memory pool, and their memory pool is not shared among objects. That is, if you allocate and release a large number of integers, the memory used to cache these integers can no longer be allocated to floating-point numbers.
Variable caching mechanism
Number type
1. For integers, -5~ the same value id in the positive infinite range is consistent
2. For floating-point numbers, the same value id in the range of non negative numbers is consistent
3. For Boolean values, IDS are consistent when the values are the same
4. Complex numbers are never the same in the structure of real + imaginary numbers (except for imaginary numbers)
Container type
1. When the string and empty tuple are the same, the address is the same
2. List, tuple, dictionary, set, id identification is different in any case [empty tuple exception]