Python3 data structure
In this chapter, we mainly introduce the Python data structure based on the knowledge points learned previously.
List
Lists in Python are variable. This is the most important feature that distinguishes them from strings and tuples. In one sentence, the list can be modified, and Strings and tuples cannot.
The following are the methods of lists in Python:
Method | Description |
---|---|
list .append(x) | Adds an element to the end of the list, equivalent to a[len(a):] = [x]. |
list.extend(L) | Extends the list by adding all elements of the specified list, 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, a.insert(0, x) will be inserted before the entire list, and a.insert(len(a), x) is equivalent to a.append( x). |
list.remove(x) | Remove the first element with value x in the list. If there is no such element, an error will be returned. |
list.pop([i]) | Removes an element from the specified position in the list and returns it. If no index is specified, a.pop() returns the last element. The element is removed from the list. (The square brackets around i in the method indicate that this parameter is optional, rather than requiring you to enter a pair of square brackets. You will often encounter such marks in the Python library reference manual.) |
list.clear() | Removes all items in the list, equal to del a[:]. |
list.index(x) | Returns the index of the first element in the list with value x. If there are no matching elements, an error will be returned. |
list.count(x) | Returns the number of times x appears in the list. |
list.sort() | Sort the elements in the list. |
list.reverse() | Reverse the elements in the list. |
list.copy() | Returns a shallow copy of the list, equal to a[:]. |
The following example demonstrates most of the methods of 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 that modify the list such as insert, remove or sort have no return value.
Use the list as a stack
The list method makes it easy to use the list as a stack. The stack is a specific data structure. The first element entered is the last one to be released. (Last in, first out). Use the append() method to add an element to the top of the stack. An element can be released from the top of the stack 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, but the first element added to the queue is the first to be taken out; but if Lists are not efficient for this purpose. Adding or popping elements from the end of the list is fast, but inserting or popping elements from the head of 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 arrival deque(['Michael', 'Terry', 'Graham'])
List comprehensions
List comprehensions provide a simple way to create lists from sequences. Typically applications apply some operations to each element of a sequence and use the result as an element to generate a new list, or create a subsequence based on certain criteria.
Every list comprehension begins with for followed by an expression, and then zero or more for or if clauses. The return result is a list generated from the following for and if contexts based on the expression. If you want the expression to derive a tuple, you must use parentheses.
Here we multiply each value in the list by three to obtain a new list:
>>> vec = [2, 4, 6] >>> [3*x for x in vec] [6, 12, 18]
Now we play a little trick:
>>> [[x, x**2] for x in vec] [[2, 4], [4, 16], [6, 36]]
Here we multiply each value in the sequence Call a method one element at a time:
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit']
We can use if clauses as filters:
>>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] []
Here are some demonstrations of 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]
List Comprehensions 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 analysis
Python lists can also be nested.
The following example shows a 3X4 matrix list:
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ]
The following example converts a 3X4 matrix list into a 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 example can also be implemented using the following method :
>>> 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
Use the del statement to delete an element from a list by index rather than value. This is different from using pop() to return a value. You can use the del statement to delete a cut from a list, or to 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 entity variables:
>>> del a
Tuples and sequences
Tuples consist 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 are always output with parentheses to facilitate the correct expression of nested structures. It may or may not be entered with parentheses, but parentheses are usually required (if the tuple is part of a larger expression).
Set
A set is an unordered set of non-repeating elements. Basic functionality includes relationship testing and elimination of duplicate elements.
You can use curly brackets ({}) to create a collection. Note: If you want to create an empty collection, you must use set() instead of {}; the latter creates an empty dictionary, a data structure we will introduce in the next section.
The following is a simple demonstration:
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in either a or b {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'}>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in either a or b {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'}
Sets also support comprehensions:
>>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'}
Dictionaries
Another very useful Python library The built data type is a dictionary.
Unlike sequences, which are indexed by continuous integers, dictionaries are indexed by keywords, which can be any immutable type, usually strings or numeric values.
The best way to understand a dictionary is to think of it as an unordered collection of key => value pairs. Within the same dictionary, keywords must be different from each other.
A pair of braces creates an empty dictionary: {}.
This is a simple example of dictionary use:
>>> 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 tel True >>> 'jack' not in tel False
The constructor dict() builds a dictionary directly from a list of key-value pair tuples. List comprehensions specify specific key-value pairs if there is a fixed pattern:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
Additionally, dictionary comprehensions can be used to create expression dictionaries of arbitrary keys and values:
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}
if keyword Just a simple string, it is sometimes more convenient to use keyword parameters to specify key-value pairs:
>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127}
Traversal skills
When traversing in a dictionary, keywords and corresponding values can Use the items() method to interpret it simultaneously:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
When traversing 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
Traverse two or more at the same time The sequence can be combined using zip():
>>> 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, first specify the sequence, and then call the reversesd() function:
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1
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) ... apple banana orange pear
See the documentation
Python3 list
Python3 Tuple
Python3 Dictionary