In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what are the knowledge points of Python3 data structure". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the knowledge points of Python3 data structure?"
Digital Number
Integer (int)-often referred to as an integer or integer, is a positive or negative integer without a decimal point. Python3 integers are unlimited in size and can be used as Long types. Bool is a subtype of integers.
Floating point type (float)-A floating point type consists of an integer part and a fractional part, and can also be represented by scientific counting (2.5e2 = 2.5x 102250)
The complex number ((complex))-the complex number consists of the real part and the imaginary part, which can be denoted by a + bj or complex (aline b). Both the real part an and the imaginary part b of the complex number are of floating point type.
Digital type conversion
Int (x) converts x to an integer.
Float (x) converts x to a floating point number.
Complex (x) converts x to a complex number, where the real part is x and the imaginary part is 0.
Complex (x, y) converts x and y to a complex number, where the real part is x and the imaginary part is y. X and y are numeric expressions.
Numeric operation # +-* /% (remainder) * * (exponentiation) # in integer division, division / always returns a floating point number. # if you only want to get the result of an integer and discard possible fractions, you can use the operator / / print (8 / 5) # 1.6print (8 / / 5) # Note: / / you don't necessarily get a number of integer type. It is related to the data type of the denominator print (8 / / 5. 0) # 1. Query the square 25 string str string of the exponentiation print (5 * 2) # 5 using the * * operation
Index (): finds the location where the substring substr appears for the first time, and throws a ValueErrorrindex () exception if the substring does not exist
Rindex (): finds the location of the last occurrence of the substring substr, and throws a ValueError () exception if the substring does not exist
Find (): finds the location where the substring substr appears for the first time, and returns-1 if the substring does not exist
Rfind (): finds the location of the last occurrence of the substring substr, and returns-1 if the substring does not exist
S = 'hello, hello'print (s.index (' lo')) # 3print (s.find ('lo')) # 3print (s.find (' k')) #-1print (s.rindex ('lo')) # 10print (s.rfind (' lo')) # 10 string case conversion
Upper (): converts all characters in a string to uppercase letters
Lower (): converts all characters in a string to lowercase letters
Swapcase (): converts all uppercase letters in a string to lowercase letters and all lowercase letters to uppercase letters
Capitalize (): converts the first character to uppercase and the rest to lowercase
Title (): converts the first character of each word to uppercase and the remaining characters of each word to lowercase
S = 'hello, Python'print (s.upper ()) # HELLO, PYTHONprint (s.lower ()) # hello, pythonprint (s.swapcase ()) # HELLO, pYTHONprint (s.capitalize ()) # Hello, pythonprint (s.title ()) # Hello, Python string alignment
Center (): Center alignment. The first parameter specifies the width, and the second parameter specifies the filler. The default is space. If the set width is less than the actual width, the original string is returned.
Ljust (): left alignment, the first parameter specifies the width, the second parameter specifies the filler, the default is a space, and if the set width is less than the actual width, the original string is returned
Rjust (): right-aligned, the first parameter specifies the width, the second parameter specifies the filler, the default is a space, and the original string is returned if the set width is less than the actual width
Zfill (): align to the right and fill the left with 0. This method takes only one parameter to specify the width of the string. If the specified width is less than or equal to the length of the string, the string itself is returned.
S = 'hello,Python'''' Center alignment' print (s.center (20,'*')) # * hello,Python****''' left alignment''print (s.ljust (20,' *')) # hello,Python*print (s.ljust (5,'*)) # hello,Python''' right alignment''print (s.rjust (20) ('*')) # * hello,Python''' right align, fill with 0''print (s.zfill (20)) # 000000hellodPythonprint ('-1005'.zfill (8)) #-0001005 string splitting, slicing
Split
Split (): split from the left side of the string
Rsplit (): splits from the right side of the string
The default split character is a space, and the return value is a list
Specify the splitter of the split string through the parameter sep
Specify the maximum number of times to split the parity string through the parameter maxsplit. After the maximum number of splits, the remaining substrings will be taken as a separate part.
S = 'hello word Python'print (s.split ()) # [' hello', 'word',' Python'] S1 = 'hello | word | Python'print (s1.split (sep=' |')) # ['hello',' word', 'Python'] print (s1.split (' | |, 1)) # ['hello',' word | Python'] # start print (s1.rsplit ('| |, 1)) # ['hello | word' 'Python'] # start on the right
Slice
S = 'hello,world'print (s [: 5]) # hello starts at index 0 and ends at 4 print (s [6:]) # world starts at index 6 and goes to the last element print (s [1: 5:1]) # ello starts at index 1 and ends at 4 with a step of 1print (s [:: 2]) # hlowrd from start to end and a step of 2print (s [:-1]) # dlrow,olleh Starting from the last element (index-1), to the end of the first element print (s [- 6 1]) #, world starts from index-6 to the last end string to determine the correlation
Isidentifier (): determines whether the specified string is a legal identifier
Isspace (): determines whether the specified string consists entirely of white space characters (carriage return, line feed, horizontal tab)
Isalpha (): determines whether the specified string is composed entirely of letters
Isdecimal (): determines whether the specified string consists entirely of decimal numbers
Isnumeric (): determines whether the specified string is composed entirely of numbers
Isalnum (): determines whether the specified string consists entirely of letters and numbers
String other operations
String substitution
Replace ()
S = 'hello,Python,Python,Python'print (s.replace (' Python', 'Java')) # replace all hello,Java,Java,Javaprint by default (s.replace (' Python', 'Java', 2)) # set the number of replacements hello,Java,Java,Python
String concatenation
Join ()
Lst = ['hello',' java', 'Python'] print (', '.join (lst)) # hello,java,Pythonprint (' | '.join (lst)) # hello | java | output of Python format string
% placeholder: add% before output, multiple parameters with parentheses and commas
% s string
Integer% I or% d
-% f floating point number
{} placeholder: call the format () method
F-string: write variables in {}
Name = 'Zhang San' age = 20print ('my name is% s, this year% d year'% (name, age)) print ('my name is {0}, this year {1} year, nickname is also {0} (name, age)) print (f'my name is {name}, this year {age} year') # my name is Zhang San, I am 20 years old this year, my nickname is Zhang San # my name is Zhang San, I am 20 years old this year
Set the width and precision of the number
# set width and precision of digits''% occupancy 'print (' d'% 99) # 10 indicates width print ('.3f'% 3.1415926) # .3f represents 3 decimal places print ('.3f'% 3.1415926) # both width and precision''{} placeholder need to be used: start''print (' {: .3} '.format (3.1415926) ) # .3 represents 3 significant digits print ('{: .3f} '.format (3.1415926)) # .3f represents the last 3 decimal places print (' {: 10.3f} '.format (3.1415926)) # .3f represents the last 3 decimal places # 99' 3.14 '3.142' 3.14 '3.14' 3.142 string encoding s = 'long-lasting' # Encoding converts a string to byte (binary) data print (s.encode (encoding='gbk')) # gbk Chinese occupies 2 bytes print (s.encode (encoding='utf-8')) # utf-8, Chinese occupies 3 bytes # decoding converts byte (binary) into string data # encoding and decoding The encoding method requires consistent byte = s.encode (encoding='gbk') print (byte.decode (encoding='gbk')) # b'\ xb5\ xab\ xd4\ xb8\ xc8\ xcb\ xb3\ xa4\ xbe\ xc3'# b'\ xe4\ xbd\ x86\ x84\ xbf\ xe4\ xba\ xba\ xe9\ x95\ xbf\ xe4\ xb9\ x85 wish the characteristics of the list list
Ordered sequence
Index mapping only one data
Duplicate data can be stored
Mixed storage of any data type
Dynamically allocate and reclaim memory as needed
Creation of list
[]: use square brackets
List (): use the built-in function list ()
List generation
Syntax format: [iTuni for i in range (I, 10)]
Explanation: I represents a custom variable, I represents an expression of a list element, and range (I, 10) represents an iterable object
Print ([I * i for i in range (1,10)]) # [1, 4, 9, 16, 25, 36, 49, 64, 81] list element query
Determine whether the specified element exists in the list
In / not in
Traversal of list elements
For item in list: print (item)
Query element index
List.index (item)
Get element
List = [1, 4, 9, 16, 25, 36, 49, 64, 81] print (list [3]) # 16print (list [3:6]) # [16, 25, 36] addition of list elements
Append (): add an element to the end of the list
Extend (): add at least one element to the end of the list
Insert0: adds an element at the specified location in the list
Slicing: adding at least one element at a specified location in the list
Deletion of list elements
Rerove (): delete one element at a time
Duplicate element deletes only the first one
There is no ValceError exception thrown in the element
Pop (): deletes an element at a specified index location
No IndexError exception is thrown in the specified index
Delete the last element in the list without specifying an index
Slicing: delete at least one element at a time
Clear0: clear the list
Del: delete list
Sorting of list elements
Sort (), all elements in the list are sorted in the order from smallest to largest by default. You can specify reverse= True to sort in descending order, which is an operation on the original list.
List.sort ()
Sorted (), you can specify reverse-True to sort in descending order, so that the original list does not change and a new list is generated.
Summary of sorted (list) knowledge points
The characteristics of tuple tuples.
Tuples in Python are similar to lists, except that the elements of tuples cannot be modified.
Tuples use parentheses and lists use square brackets
Creation of tuples
Use parentheses () directly. Parentheses can be omitted
T = ('Python',' hello', 90)
Using the built-in function tuple (), if there are multiple elements, you must add parentheses
Tuple (('Python',' hello', 90))
A tuple that contains only one element, using parentheses and commas
T = (10,) summary of knowledge points
The characteristics of the dictionary dict
Stored as key-value pairs, key is unique
Key must be an immutable object
Dictionaries are variable sequences
Dictionaries are unordered sequences (Note: since the Python3.7 version, the insertion order retention nature of dict objects has been declared as an official part of the Python language specification. That is, after Python3.7, the dictionary is an ordered sequence, and the order is the insertion order of the dictionary)
The creation of a dictionary
{}: use curly braces
Use the built-in function dict ()
Zip (): dictionary generator
Items = ['fruits',' Books', 'Others'] prices = [12, 36, 44] d = {item.upper (): price for item, price in zip (items, prices)} print (d) # {' FRUITS': 12, 'BOOKS': 36,' OTHERS': 44} dictionary element acquisition
[]: [] value
Scores [Zhang San]. If key does not exist, throw a keyError exception
The get (): get () method takes a value. If key does not exist, None is returned. You can also set the default return value.
New dictionary element user = {"id": 1, "name": "zhangsan"} user ["age"] = 25print (user) # {'id': 1,' name': 'zhangsan',' age': 25} dictionary element modification user = {"id": 1, "name": "zhangsan", "age": 25} user ["age"] = 18print (user) # {'id': 1,' name': zhangsan'' Deletion of 'age': 18} dictionary elements
Del: delete a specified key-value pair or delete a dictionary
User = {"id": 1, "name": "zhangsan"} del user ["id"] print (user) # {'name':' zhangsan'} del user
Claer (): clear the elements in the dictionary
User = {"id": 1, "name": "zhangsan"} user.clear () print (user) # {} get dictionary view
Keys (): gets all the key in the dictionary
Values (): gets all the value in the dictionary
Items (): gets all key,value key-value pairs in the dictionary
Traversal of dictionary elements
Traverse key, and then get value through key
Scores = {'Zhang San': 100,'Li Si': 95, 'Wang Wu': 88} for name in scores: print (name, scores [name])
Traversing key,value at the same time through the items () method
Scores = {'Zhang San': 100,' Li Si': 95, 'Wang Wu': 88} for name, score in scores.items (): summary of knowledge points of print (name, score)
The characteristics of set sets
The set is a variable sequence.
Collections are dictionaries without value
Elements in the collection do not repeat
The elements in the collection are unordered
Creation of a collection
{}
S = {'Python',' hello', 90}
Built-in function set ()
Print (set ("Python")) print (set (range (1pr 6)) print (set ([3,4,7]) print (set ((3,2,0)) print (set ({"a", "b", "c"})) # defines an empty set: set () print (set ())
Set generation
Print ({I * i for i in range (1,10)}) # {64, 1, 4, 36, 9, 16, 49, 81, 25} set operation
Judgment operation of set elements
In / not in
New operations for collection elements
Add (): add one element at a time
Update (:) adds multiple elements
Delete operation of collection element
Remove (): deletes a specified element and throws a KeyError if the specified element does not exist
Discard (:) deletes a specified element and does not throw an exception if the specified element does not exist
Pop (): randomly delete an element
Clear (): clear the collection
The relationship between sets
Whether two sets are equal: you can use the operator = = or! = to determine whether the elements are equal as long as the elements are the same
Whether one set is a subset of another: issubset ()
S1 = {10,20,30,40,50,60} S2 = {10,30,40} S3 = {10,70} print (s2.issubset (S1)) # Trueprint (s3.issubset (S1)) # False
Whether one set is a superset of another: issuperset ()
Print (s1.issuperset (S2)) # Trueprint (s1.issuperset (S3)) # False
Whether the two sets do not intersect: isdisjoint ()
S1 = {10,20,30,40,50,60} S2 = {10,30,40} s3 = {20,70} print (s1.isdisjoint (S2)) # False with intersection print (s3.isdisjoint (S2)) # True mathematical operation without intersection set
Intersection: intersection () and & equivalence, the intersection of two sets
S1 = {10,20,30,40} S2 = {20,30,40,50,60} print (s1.intersection (S2)) # {40,20,30} print (S1 & S2) # {40,20,30}
Union: union () and | equivalent, the union of two sets
Print (s1.union (S2)) # {40,10,50,20,60,30} print (S1 | S2) # {40,10,50,20,60,30}
Difference sets: difference () and-equivalent
Print (s2.difference (S1)) # {50,60} print (S2-S1) # {50,60}
Symmetric difference: symmetric_difference () is equivalent to ^
Print (s2.symmetric_difference (S1)) # {10,50,60} print (S2 ^ S1) # {10,50,60} knowledge points summary
List, tuple, dictionary, collection summary
At this point, I believe you have a deeper understanding of "what are the knowledge points of Python3 data structure?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.