Python016 Python3 data structure, python016python3
Python3 Data Structure
This section describes the Python data structure based on the knowledge points learned earlier.
List
In Python, the list is variable. This is the most important feature that distinguishes it from strings and metadata. In a word, the list can be modified, but the string and metadata cannot.
The following is a list of methods in Python:
Method |
Description |
List. append (x) |
Add an element to the end of the list, which is equivalent to a [len (a):] = [x]. |
List. extend (L) |
You can add all the elements in the specified list to expand the list, which is equivalent to a [len (a):] = L. |
List. insert (I, x) |
Insert an element at the specified position. The first parameter is the index of the element to be inserted before it, for example,. insert (0, x) is inserted before the entire list, and. insert (len (a), x) is equivalent to. append (x ). |
List. remove (x) |
Delete the first element whose value is x in the list. If no such element exists, an error is returned. |
List. pop ([I]) |
Delete an element from the specified position in the list and return it. If no index is specified, a. pop () returns the last element. The element is deleted from the list. (Square brackets on both sides of method I indicate that this parameter is optional, rather than requiring you to enter a pair of square brackets. You will often encounter this mark in the Python Library Reference Manual .) |
List. clear () |
Remove all items from the list, which is equal to del a [:]. |
List. index (x) |
Returns the index of the first x element in the list. If no matching element exists, an error is returned. |
List. count (x) |
Returns the number of times x appears in the list. |
List. sort () |
Sorts the elements in the list. |
List. reverse () |
The elements in the inverted list. |
List. copy () |
Returns the shortest copy of the list, which is equal to a [:]. |
The following example demonstrates most of the methods in the list:
>>> a = [66.25, 333, 333, 1, 1234.5]>>> print(a.count(333), a.count(66.25), a.count('x'))2 1 0>>> a.insert(2, -1)>>> a.append(333)>>> a[66.25, 333, -1, 333, 1, 1234.5, 333]>>> a.index(333)1>>> a.remove(333)>>> a[66.25, -1, 333, 1, 1234.5, 333]>>> a.reverse()>>> a[333, 1234.5, 1, 333, -1, 66.25]>>> a.sort()>>> a[-1, 1, 66.25, 333, 333, 1234.5]
Note: methods like insert, remove, or sort that modify the list do not return values.
Use the list as a stack
The list method makes it easy to use the list as a stack. the stack is used as a specific data structure, and the last element that first enters is released (first, and foremost ). You can use the append () method to add an element to the top of the stack. You can release an element from the top of the stack by using the pop () method without specifying an index. For example:
>>> stack = [3, 4, 5]>>> stack.append(6)>>> stack.append(7)>>> stack[3, 4, 5, 6, 7]>>> stack.pop()7>>> stack[3, 4, 5, 6]>>> stack.pop()6>>> stack.pop()5>>> stack[3, 4]
Use the list as a queue
You can also use the list as a queue. It is only the first element added to the queue and the first element is retrieved. However, it is inefficient to use the list for such purposes. Adding or popping up elements at the end of the list is fast, but inserting or popping up elements from the list is not fast (because all other elements have to be moved one by one ).
>>> from collections import deque>>> queue = deque(["Eric", "John", "Michael"])>>> queue.append("Terry") # Terry arrives>>> queue.append("Graham") # Graham arrives>>> queue.popleft() # The first to arrive now leaves'Eric'>>> queue.popleft() # The second to arrive now leaves'John'>>> queue # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])
List Derivation
List derivation provides a simple way to create a list from a sequence. Generally, an application applies some operations to each element of a sequence, and uses the obtained results as the elements for generating a new list, or creates a subsequence Based on the determined criteria.
Each list derivation is followed by an expression after the for clause, and then there are no to multiple for or if clauses. The returned result is a list generated from the for and if context after the expression. If you want the expression to export a tuples, you must use parentheses.
Here we multiply each value in the list by three to get a new list:
>>> vec = [2, 4, 6]>>> [3*x for x in vec][6, 12, 18]
Now let's take a look:
>>> [[x, x**2] for x in vec][[2, 4], [4, 16], [6, 36]]
Here we call a method one by one for each element in the sequence:
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']>>> [weapon.strip() for weapon in freshfruit]['banana', 'loganberry', 'passion fruit']
We can use the if clause as a filter:
>>> [3*x for x in vec if x > 3][12, 18]>>> [3*x for x in vec if x < 2][]
Here are some demos about loops and other techniques:
>>> 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 range(len(vec1))][8, 12, -54]
The list derivation can use complex expressions or nested functions:
>>> [str(round(355/113, i)) for i in range(1, 6)]['3.1', '3.14', '3.142', '3.1416', '3.14159']
Nested list Parsing
The Python list can also be nested.
The following example shows a matrix of 3x4:
>>> matrix = [... [1, 2, 3, 4],... [5, 6, 7, 8],... [9, 10, 11, 12],... ]
The following example converts the 3x4 matrix list to the 4x3 list:
>>> [[row[i] for row in matrix] for i in range(4)][[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
The following examples can also be implemented using the following methods:
>>> transposed = []>>> for i in range(4):... transposed.append([row[i] for row in matrix])...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Another implementation method:
>>> transposed = []>>> for i in range(4):... # the following 3 lines implement the nested listcomp... transposed_row = []... for row in matrix:... transposed_row.append(row[i])... transposed.append(transposed_row)...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Del statement
The del statement can be used to delete an element from a list based on indexes rather than values. This is different from a value returned by using pop. You can use the del statement to delete a cut from the list or clear the entire list (the method we introduced previously was to assign an empty list to the cut ). For example:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>> del a[2:4]>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[]
You can also use del to delete object variables:
>>> del a
Tuples and Sequences
Tuples are composed of several comma-separated values, for example:
>>> t = 12345, 54321, 'hello!'>>> t[0]12345>>> t(12345, 54321, 'hello!')>>> # Tuples may be nested:... u = t, (1, 2, 3, 4, 5)>>> u((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
As you can see, tuples always have parentheses in the output to correctly express the nested structure. There may be or no parentheses in the input, but parentheses are usually required (if the tuples are part of a larger expression ).
Set
A set is a set of unordered and non-repeating elements. Basic functions include link testing and deduplication.
You can use braces ({}) to create a set. Note: To create an empty set, you must use set () instead of {}; To create an empty dictionary. The data structure will be introduced in the next section.
The following is a simple demonstration:
>>> Basket = {'apple', 'Orange ', 'apple', 'pear', 'Orange ', 'Banana' }>>> print (basket) # Delete duplicate {'Orange ', 'Banana', 'pear ', 'apple' >>>> 'Orange 'in basket # Check member True >>> 'crabgrass' in basketFalse >>## the following demonstrates the operations on two sets...>> a = set ('abracadaba') >>> B = set ('acazam') >>> a # unique letter in a {'A', 'R ', 'B', 'C', 'D' }>>> a-B # The letter in a, but not in B {'R', 'D ', 'B' }>>> a | B # letters in a or B {'A', 'C', 'R', 'D', 'B ', 'M', 'z', 'L'} >>> a & B # All letters in a and B {'A ', 'C' }>>> a ^ B # letters in a or B, but not both in a and B {'R', 'D', 'B ', 'M', 'z', 'L '}
The Set also supports derivation:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}>>> a{'r', 'd'}
Dictionary
Another useful Python built-in data type is dictionary.
The sequence is indexed by continuous integers. Different from this, the dictionary uses the keyword as the index. The keyword can be of any immutable type and usually uses a string or a value.
The best way to understand the dictionary is to regard it as a disordered key => value pair set. In the same dictionary, the keywords must be different.
Create an empty dictionary with a pair of braces :{}.
This is a simple example of dictionary usage:
>>> 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}>>> list(tel.keys())['irv', 'guido', 'jack']>>> sorted(tel.keys())['guido', 'irv', 'jack']>>> 'guido' in telTrue>>> 'jack' not in telFalse
The constructor dict () directly constructs a dictionary from the list of key-value pairs. If there is a fixed pattern, the list derivation specifies a specific key-Value Pair:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]){'sape': 4139, 'jack': 4098, 'guido': 4127}
In addition, Dictionary derivation can be used to create an expression dictionary for any key and value:
>>> {x: x**2 for x in (2, 4, 6)}{2: 4, 4: 16, 6: 36}
If the keyword is a simple string, it is more convenient to use the keyword parameter to specify the key-Value Pair:
>>> dict(sape=4139, guido=4127, jack=4098){'sape': 4139, 'jack': 4098, 'guido': 4127}
Traversal skills
In the dictionary, the keywords and corresponding values can be interpreted using the items () method at the same time:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.items():... print(k, v)...gallahad the purerobin the brave
In the time series, you can use the enumerate () function to obtain the index position and corresponding value at the same time:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):... print(i, v)...0 tic1 tac2 toe
Traverse two or more sequences at the same time. You can use a zip () combination:
>>> questions = ['name', 'quest', 'favorite color']>>> answers = ['lancelot', 'the holy grail', 'blue']>>> for q, a in zip(questions, answers):... print('What is your {0}? It is {1}.'.format(q, a))...What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue.
To traverse a sequence in reverse direction, specify the sequence and call the reversed () function:
>>> for i in reversed(range(1, 10, 2)):... print(i)...97531
To traverse a sequence in order, use the sorted () function to return a sorted sequence without modifying the original value:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):... print(f)...applebananaorangepear
Python3 Function
Note list
The tuples are unchangeable. If the tuples have variable member types, the members can be edited.
a = [1,2,3,4]b = [5,6,7,8]c = [9,10,11,12]t = a,b,cprint(t)del b[1:4]print(t)
Output:
([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])([1, 2, 3, 4], [5], [9, 10, 11, 12])