?
Subdirectory
5.1 In-depth linked list
5.1.1 Connecting the Links as a Stack Using 5.1.2 Linches as a queue Use 5.1.3 Functional Programming Tools 5.1.4 Link Pictures 5.2 Del Statement 5.3 Topology (SEQUENCES) 5.4 Dictionary (Dictionaries) 5.5 Circular Skills 5.6 In-depth Condition Control 5.7 Compare Sequences (SEQUENCES) and other types
? 5. Data structure
This chapter explains some things you have learned and have added new content.
? 5.1 in-depth linked list
There are many ways to list the table, here is all methods of the chain table:
Append (x)
Add an element to the end of the linked list, which is equivalent to
a [len (a):] = [x]
.
Extend (L)
Expand the chain list by adding all the elements of the specified list, it is equivalent to
a [len (a):] = L
.
INSERT (i, x)
Insert an element in the specified location. The first parameter is the index of the element inserted in front of it, for example
A. INSERT (0, x) before being inserted into the entire linked list, and
A.Nsert (Len (a), x) is equivalent to
a.append (x)
.
Remove (x)
Delete the value of the list
The first element of x. If there is no such element, it will return an error.
POP ([i])
Delete the element from the specified location of the linked list and returns it. If no index is specified,
A.POP () Returns the last element. The element is then deleted from the list. (In the method
The square brackets on both sides indicate that this parameter is optional, not asking you to enter a pair of brackets, you will often
Such markers are encountered in the Python Library Reference Manual. )
Index (x)
The first value in the return list is
The index of the elements of x. If there is no matching element, an error will be returned.
Count (x)
return
X The number of times that appears in the linked list.
sort ()
The elements in the linked list are properly sorted.
Reverse ()
Elements in the chain table.
Below this example demonstrates most of the methods of the linked list:
>>> a = [66.6, 333, 333, 1, 1234.5]
>>> Print A.count (333), A.count (66.6), A.Count ('x')
2 1 0
>>> a.insert (2, -1)
>>> A.Append (333)
>>> a
[66.6, 333, -1, 333, 1, 1234.5, 333]
>>> a.index (333)
1
>>> a.Remove (333)
>>> a
[66.6, -1, 333, 1, 1234.5, 333]
>>> a.Reverse ()
>>> a
[333, 1234.5, 1, 333, -1, 66.6]
>>> A.SORT ()
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
5.1.1 Take the Link Watch as a Stack Used
The chain method allows the linked list to be used as a stack, the stack is such a data structure, the most entered element is released (the next first out). Use the append () method to add an element to the top of the stack. The POP () method that does not specify an index can release an element from the stack top. E.g:
>>> stack = [3, 4, 5]
>>> stack.Append (6)
>>> stack.Append (7) >>> stack
[3, 4, 5, 6, 7]
>>> stack.pop ()
Seduce
>>> Stack
[3, 4, 5, 6]
>>> stack.pop ()
6
>>> stack.pop ()
5
>>> Stack
[3, 4]
5.1.2 Take the list as a queue
You can also use the list as a queue, the queue is such a data structure, the first entry element is first released (advanced first out). Using the append () method can add the element to the queue finally, call the POP () method for the parameter to release the first entry element. E.g:
>>> queue = ["Eric", "John", "Michael"]
>>> Queue.Append ("Terry") #TERRY ARRIVES
>>> Queue.Append ("graham") # graham arrives
>>> queue.pop (0)
'ERIC'
>>> queue.pop (0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']
5.1.3 Function Programming Tools
For linked lists, there are three built-in functions: filter (), map (), and reduuce ().
"FILTER (FUNCTION, SEQUENCE" returns a sequence, including an element that returns a value true after all call function (items) in a given sequence. (If possible, the same type will be returned). For example, the following procedure can calculate the number of partial prime:
>>> DEF F (x): return x% 2! = 0 and x% 3! = 0
...
>>> Filter (f, Range (2, 25))
[5, 7, 11, 13, 17, 19, 23]
"MAP (Function, Sequence" is called for each element and returns the return value into a linked list for each element. For example, the following program calculates the cube:
>>> DEF CUBE (X): Return X * x * x
...
>>> Map (Cube, Range (1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
You can pass multiple sequences, and the function must have a corresponding number of parameters. When executed, use the elements corresponding to each sequence to call the function (if some sequences are shorter than other short, use none instead). If None is incorporated into a function, the direct return parameters are replaced.
These two situations we will find "MAP (None, List1, List2) is a convenient way to turn a pair of sequences into elements. E.g:
>>> SEQ = RANGE (8)
>>> Def Square (x): return x * x
...
>>> Map (None, SEQ, MAP (Square, SEQ))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] " Returns a single value, which is constructed in this way: first call the function in the first two elements of the sequence, and then call the return value and the third parameter. For example, the following programs calculate the sum of 1 to 10:
>>> DEF ADD (X, Y): Return X Y
...
>>> Reduce (Add, Range (1, 11))
55
If there is only one element in the sequence, it returns it, and if the sequence is empty, you will throw an exception.
You can pass the third parameter as the initial value. If the sequence is empty, return to the initial value, otherwise the function will first receive the first element of the initial value and the sequence, and then the return value and the next element, so on. E.g:
>>> DEF SUM (SEQ):
... DEF Add (x, y): Return X Y
... Return Reduce (Add, SEQ, 0)
...
>>> SUM (Range (1, 11))
55
>>> SUM ([])
0
Do not define so as examples in the example: Because the total value is a universal demand, the built-in SUM (Sequence) function is provided in the new version 2.3.
5.1.4 Link Picture Detection
Link list provides a simple way to create a list without using MAP (), Filter (), and lambda. The definition of the returned linked list is usually clearer than the created list. Each chain list includes an expression, zero or more for or if statements after a For statement. The return value is a linked list that consists of an element obtained by the expression after the FOR or IF clause. If you want to get a topology, you must add parentheses.
>>> Freshfruit = ['Banana', 'loganberry', 'passes fuit']
>>> [weapon.strip () for weapon in freshfruit]
['Banana', 'loganberry', 'passion struit']
>>> VEC = [2, 4, 6]
>>> [3 * x for x in vec]
[6, 12, 18]
>>> [3 * x for x in Vec IF X> 3]
[12, 18]
>>> [3 * x for x in Vec IF x <2]
[]
>>> [[xi x ** 2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
>>> [x, x ** 2 for x in vec] # Error - Parens Required for tuples
File "
", LINE 1, IN?"
[x, x ** 2 for x in vec]
^
SyntaxError: Invalid Syntax
>>> [(x, x ** 2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
>>> VEC1 = [2, 4, 6]
>>> VEC2 = [4, 3, -9]
>>> [x * y for x in vec1 for y in VEC2] [8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [VEC1 [I] * VEC2 [I] for i in inheng (len (vec1))]
[8, 12, -54]
To make the chain pilot matching the behavior of the For loop, the loop variable can be reserved outside of the derivation:
>>> x = 100 # this gets overwritten
>>> [x ** 3 for x in Range (5)]
[0, 1, 8, 27, 64]
>>> x # the final value for weight (5)
4
? 5.2 DEL statement
There is a way to remove the element of the specified index from the list: DEL statement. This method can also delete the slice from the linked list (before we assign an empty list to the slice). E.g:
>>> a = [-1, 1, 66.6, 333, 333, 1234.5]
>>> DEL A [0]
>>> a
[1, 66.6, 333, 333, 1234.5]
>>> DEL A [2: 4]
>>> a
[1, 66.6, 1234.5]
Del can also be used to delete the entire variable:
>>> DEL A
Thereafter, the name will then be an error (at least to give it another value). Later we will also find other usages of DEL.
? 5.3 Topology (TUPLES) and sequences (SEQUENCES)
We know that there are many universal properties such as indexes and slice operations. They are two kinds of sequence types. Because Python is a language inactivating, other sequence types can also be added, here there is another standard sequence type: topology.
A topology consists of several comma-separated values, for example:
>>> T = 12345, 54321, 'Hello!'
>>> T [0]
12345
>>> T
(12345, 54321, 'Hello!')
>>> # tPLES May Be Nested:
... u = t, (1, 2, 3, 4, 5)
>>> U
((12345, 54321, 'Hello!'), (1, 2, 3, 4, 5)))
As you can see, the topology is always in the output, so that the nested structure is properly expressed. There may be or without parentheses when entering, but often brackets are necessary (if the topology is part of a larger expression).
There are many uses in topology. For example, (x, y) coordinate points, employee records in the database, and more. The topology is like a string, which cannot be changed: a separate element that cannot give the topology (although you can simulate by joining and slice). It is also possible to create a topology, such as a chain list by including a variable object.
A special problem is to construct a topology containing zero or one element: In order to adapt to this situation, there are some additional changes on the grammar. A pair of air parentheses can create a null topology; to create a single element topology can be followed by a comma behind the value (not enough in parentheses). Ugly, but effective. For example: >>> EMPTY = ()
>>> Singleton = 'Hello', # <- Note Trailing CommA
>>> LEN (EMPTY)
0
>>> LEN (Singleton)
1
>>> Singleton
('Hello',)
The statement T = 12345, 54321, 'Hello!' Is an example of a topological package: values 12345, 54321, and 'Hello!' Are encapsulated into the topology. Its reverse operation may be like this:
>>> x, y, z = t
This call is called a sequence unpacking. The sequence unpacking requires the number of variables on the left to the same number of elements of the sequence. Note that variable parameters (Multiple Assignment
) Is actually just a combination of topology packages and sequence unpacking!
Here is a little asymmetry: Package multi-parameters typically create a topology, and the unpacking operation can act on any sequence.
? 5.4 Dictionary (Dictionaries)
Another very useful Python built-in data type is Dictionaries. Dictionary may be called "federated memory" (`) (`) (`)" (`)" in some languages (`) (`) (`). '' '). The sequence is indexed in a continuous integer, in connection with this, the dictionary is indexed by keywords, and the keyword can be arbitrarily non-variable type, usually using a string or value. If only strings and numbers are included in the topology, it can be used as a keyword, and if it directly or indirectly contains variable objects, it cannot be used as a keyword. You cannot use a chain list because the linked list can be used to instantly change with their APPEND () and Extend () methods, or by searching or by retrieving variables.
The best way to understand the dictionary is to see it as unordered keyword: Value (key: value pairs) collection, keywords must be different (within the same dictionary). A pair of braces create an empty dictionary: {}. When the initialized chain table, place a comma-separated keyword in the braces: value pair, this is also the way the dictionary is output.
The main operation of the dictionary is stored and paid according to keywords. You can also use DEL to delete keywords: value pair. If you store the value with a keyword already existing, the value assigned to the keyword before it will be forgotten. Trying to draw a read value from a non-existent keyword can cause an error.
The keys () method of the dictionary returns a list of all keywords, which is uncertaintable (if you need it ordered, you can only call the sort () method of the keyword list. Use the HAS_KEY () method of the dictionary to check if there is a certain keyword in the dictionary.
This is a small example of a dictionary application:
>>> Tel = {'Jack': 4098, 'Sape': 4139}
>>> Tel ['Guido'] = 4127 >>> Tel
{'Sape': 4139, 'Guido': 4127, 'Jack': 4098}
>>> TEL ['Jack']
4098
>>> DEL TEL ['SAPE']
>>> Tel ['Irv'] = 4127
>>> Tel
{'Guido': 4127, 'IRV': 4127, 'Jack': 4098}
>>> TEL.KEYS ()
['Guido', 'IRV', 'Jack']
>>> Tel.has_Key ('Guido')
True
The dictionary can be configured directly from the dictionary in the linked list. Keyword-Value For from a mode, you can use a chain to derive a simple express keyword-value chain list.
>>> DICT ([('Sape', 4139), ('Guido', 4127), ('Jack', 4098)])
{'SAPE': 4139, 'Jack': 4098, 'Guido': 4127}
>>> DICT ([(x, x ** 2) for x in vec] # ue l l omen
{2: 4, 4: 16, 6: 36}
? 5.5 cycle skills
When cycling in a dictionary, the keywords and corresponding values can be interpreted simultaneously with the items () method.
>>> Knights = {'gallahad': 'The pure', 'Robin': 'The Brave'}
>>> fork, v in knights.Items ():
... Print K, V
...
Gallahad the pure
Robin the BRAVE
When cycles in the sequence, the index position and corresponding value can be obtained simultaneously using the enumerate () function.
>>> for i, v in enumerate (['tic', 'tac', 'toe']):
... Print I, V
...
0 TIC
1 TAC
2 TOE
At the same time, two or more sequences can be circulated, and it can be interpreted using ZIP ().
>>> Questions = ['Name', 'Quest', 'Favorite Color']
>>> Answers = ['Lancelot', 'The Holy Grail', 'Blue']
>>> for q, a in zip (qustions, answers):
... Print 'What is your% s? IT IS% s.'% (Q, A)
...
What is your name? It is lancelot.
What is your quothesed? It is the Holy Grail.
What is your favorite color? It is blue.
? 5.6 in-depth conditions control
The conditions for the While and IF statements include an operator than the comparison. In and NOT comparison operator review nuclear values are within one interval. The operator IS and IS NOT compare whether the two objects are the same; this is only related to variable objects such as a linked list. All comparison operators have the same priority, lower than all numerical operations.
The comparison operation can be passed. For example, a
The comparison operation can be combined by logical operators and OR, and the results of the comparison can be retrieved with NOT. The priority of these operators is lower than the comparison operator, in them, NOT has the highest priority, the OR is the lowest, so A and not b or C is equal to (a and (not b)) or C. Of course, the expression can be represented by a desired manner.
Logical operators and OR are also referred to as short-circuit operators: their parameters are resolved from left to right, once the result is determined to stop. For example, if A and C are true and B is false, A and b and c will not parse C. When a normal non-logic value is actually, the return value of the short circuit operator is usually the last variable.
The return value of the comparison or other logical expression can be assigned to one variable, for example:
>>> String1, String2, String3 = ',' Trondheim ',' Hammer Dance '
>>> Non_null = String1 or string2 or string3
>>> Non_NULL
'Trondheim'
It should be noted that Python is different from C, and the internal expression cannot be assigned. C programmers often complain, but it avoids errors that have been used in the C program: I want to misuse = operator when == in the parsing.
? 5.7 Compare sequences and other types
Sequence objects can be compared to other objects of the same type. The comparison operation is performed in the words: first compare the first two elements, if the difference determines the result of the comparison; if the same, the two elements are compared, so that all sequences are completed. Comparison. If the two elements themselves are the same type of sequence, the recursive words are compared. If all children of the two sequences are equal, they will consider the sequence equal. If a sequence is the initial subsequence of another sequence, a shorter sequence is less than one. The character of the string is in order of the single-character ASCII order. Here are some examples of comparison between the same type of sequence:
(1, 2, 3) <(1, 2, 4)
[1, 2, 3] <[1, 2, 4]
'ABC' <'c' <'Pascal' <'Python'
(1, 2, 3, 4) <(1, 2, 4)
(1, 2) <(1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('AA', 'AB')) <(1, 2, ('ABC', 'A'), 4)
It should be noted that different types of objects are legal. The output result is determined rather than arbitrary: Types are sorted by their name. Thus, a linked list is always less than a string (String), and a string is always less than one topology (TUPLE), and the like. When the numerical type is compared, the data type is unified, so 0 is equal to 0.0, and so on. 5.1 Notes
... etc .5.1
Comparison rules for different types of objects do not depend this, they may
The subsequent version of the Python language changes.