home PYTHONJAVA
 

Python3 data structure

In this chapter, we mainly introduce the Python data structure in combination with the knowledge points learned earlier.


list

The list in Python is mutable, which is the most important feature that distinguishes it from strings and tuples. In one sentence, the list can be modified, while strings and tuples cannot.

The following is a list of methods in Python:

method Description
list.append(x) adds an element to the end of the list, which is equivalent to a[len(a):] = [x].
list.extend(L) Augment the list by adding all the elements of the specified list, which is equivalent to a[len(a):] = L.
list.insert(i, x) Insert an element at the specified location. The first argument is the index of the element to be inserted in front of 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) Delete the first element in the list with a value of x. If there is no such element, an error will be returned.
list.pop([i]) Remove the 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 then 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 square bracket. You will often encounter such a mark in the Python library reference manual.)
list.clear() Remove all items in the list, equal to del a[:].
list.index(x) returns the index of the first element in the list with an value of x. If there is no matching element, an error will be returned.
list.count(x) Returns the number of times x appears in the list.
list.sort() Sorts the elements in the list.
list.reverse() Invert 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 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 modifying inserts, removes or sorts that don't return a value.


Use the list as a stack

The list method makes it easy to use the list as a stack. The stack acts as a specific data structure, and the first element that is first entered is released (last in, first out). An element can be added to the top of the stack with the append() method. An element can be released from the top of the stack with the pop() method, which does not specify an index. E.g:

>>> 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, just the first element added to the queue, the first one is taken out; but it is not efficient to use the list for such purposes. Adding or popping elements at the end of the list is fast, but inserting them in the list or popping them from the head 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 comprehension

List comprehensions provide an easy way to create lists from sequences. Usually the application applies some operations to each element of a sequence, uses the results it obtains as an element to generate a new list, or creates a subsequence based on certain determined criteria.

Each list comprehension follows an expression followed by for and then has zero or more for or if clauses. The result returned is a list generated from the context of the for and if contexts. If you want the expression to derive a tuple, 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 we 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 about loops and other tricks:

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

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

>>> 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 remove an element from a list by index rather than by value. This is different from using pop() to return a value. You can use the del statement to remove a cut from the list, or to empty the entire list (the method we introduced earlier is to assign an empty list to the cut). E.g:

>>> 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 delete entity variables with del:

>>> del a

tuples and sequences

A tuple consists of a number of 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 parenthesized when outputting, in order to correctly represent nested structures. There may or may not be parentheses when typing, but parentheses are usually required (if the tuple is part of a larger expression).


Collection

A

collection is a collection of unordered, non-repeating elements. Basic features include relational testing and elimination of repeating elements.

You can create collections with braces ({}). Note: If you want to create an empty collection, you must use set() instead of {} ; the latter creates an empty dictionary, which we will cover in the next section.

The following is a simple demo:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> print(basket) # Remove duplicates
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # Detecting members
True
>>> 'crabgrass' in basket
False
    
    >>> # The following demonstrates the operation of two collections
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # a Unique letter{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              #The letter in a, but not in b
{'r', 'd', 'b'}
>>> a | b                              # in a Or the letter in 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 in a and b
{'r', 'd', 'b', 'm', 'z', 'l'}

Collection also supports derivation:

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






welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.