Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python3 data structure


May 10, 2021 Python3


Table of contents


In this section, we introduce the Python data structure in conjunction with the knowledge points we learned earlier.


List

Lists in Python are variable, which is the most important feature that distinguishes it from strings and d'adrons, in a word: lists can be modified, while strings and d'groups cannot be modified.

Here's how to list in Python:

Method Describe
list.append(x) Adding an element to the end of the list is equivalent to a .len(a): .
list.extend(L) The list is expanded by adding all the elements of the specified list, which is equivalent to a .len(a): . .
list.insert(i, x) Insert an element at the specified location. The first argument is the index of the element that is ready to be inserted before it, for example a.insert (0, x) is inserted before the entire list, and a.insert (len(a), x) is equivalent to a.append(x).
list.remove(x) Remove the first element in the list with a value of x. If there is no such element, an error is returned.
list.pop([i]) Remove the element from the specified location in the list and return it. I f no index is specified, a.pop() returns the last element. T he element is removed from the list. ( The square brackets on both sides of the i side of the method indicate that this parameter is optional, rather than requiring you to enter a parenthesis, which you will often encounter in the Python library reference manual.)
list.clear() Remove all items from the list, equal to del a.
list.index(x) Returns the index of the first element in the list with a value of x. If there are no matching elements, an error is returned.
list.count(x) Returns the number of times x appears in the list.
list.sort() Sort the elements in the list.
list.reverse() The element in the inverted 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 such as insert, remove, or sort to modify the list do not return a value.


Use the list as a stack

The list method makes the list convenient to use as a stack, as a specific data structure, where the first entry element is the last to be released (last in, first out). Y ou can add an element to the top of the stack using the append() method. Y ou can release an element from the top of the stack using the pop() method that does not specify 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, the element that is added at the first location in the queue, the first to be taken out, but it is inefficient to use the list as a queue. Adding or popping elements at the end of the list is fast, but inserting or ejecting from the head in the list is not (because all other elements have to move 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 inference

List inference provides an easy way to create a list from a sequence. Typically, an application applies some action to each element of a sequence, uses the results obtained as an element to generate a new list, or creates subsections based on determined criteria.

Each list inference is followed by an expression after for, followed by zero to multiple for or if clauses. T he return result is a list that is generated from the subsequent for and if context based on the expression. If you want an expression to derive a d'itesosis, you must use parentheses.

Here we multiply each number 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 play a little trick:

>>> [[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 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 inferences 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 resolution

Python's list can also be nested.

The following example shows a matrix list of 3 x 4:

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

The following example converts the matrix list of 3 x 4 to a list of 4 x 3:

>>> [[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 by:

>>> 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 way to do this:

>>> 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

Using the del statement, you can remove an element from a list by index instead of value. T his is different from returning a value using pop(). Y ou can use the del statement to remove a cut from the list, or empty the entire list (the method we covered before was to give the cut an empty list). 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

Groups and sequences

A group consists of several comma-separated values, such as:

>>> 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, the mets are always parenthesed at the output to facilitate the correct expression of nested structures. You may or may not have parentheses when you enter them, but parentheses are usually required if the yuan is part of a larger expression.


Collection

A collection is a disorderly set of non-repeating elements. Basic features include relationship testing and elimination of duplicate elements.

You can create a collection with braces. Note: If you want to create an empty collection, you must use set() instead of .

Here's a simple demo:

>>> 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'}

Collections also support inference:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

Dictionary

Another very useful Python built-in data type is the dictionary.

In contrast to sequences, which are indexed by consecutive integers, dictionaries are indexed by keywords, which can be of any imm changeable type, usually strings or values.

The best way to understand a dictionary is to think of it as a disordered set of key pairs. Within the same dictionary, keywords must be different.

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

Constructor dict() builds the dictionary directly from the list of key value pairs to the yuan. If there is a fixed pattern, the list inference specifies a specific pair of key values:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dictionary inferences can be used to create expression dictionaries of any key and value:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

If the keyword is just a simple string, it is sometimes more convenient to specify a key value pair using the keyword parameters:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

Traversal tips

Over time in the dictionary, keywords and corresponding values can be interpreted simultaneously using the items() method:

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

Over time in the sequence, the index position and corresponding values 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

To 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 reverse traverse a sequence, 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 sequentially, return a sorted sequence using the sorted() function and do not modify the original value:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

See also the documentation (Python2.x). )