Latest web development tutorials

Python3 data structure

This chapter is mainly combined with the knowledge we learned earlier to introduce Python data structures.


List

Python list is variable, which is the most important feature distinguishes it from strings and tuples, namely one sentence: The list can be modified, while the strings and tuples can not.

Here's a list of Python:

method description
list.append (x) To add an item to the end of the list, equivalent to a [len (a):] = [x].
list.extend (L) By adding all the elements of the specified list to expand the list, the equivalent of a [len (a):] = L.
list.insert (i, x) Insert an item at the specified location. The first parameter is to be inserted into its index in front of the elements, such as a.insert (0, x) will be inserted before the entire list, but a.insert (len (a), x) is equivalent to a.append ( x).
list.remove (x) Removes the first element of the list whose value is x. If there is no such element, it will return an error.
list.pop ([i]) Remove elements from the specified position in this list, and return it. If you do not specify the index, a.pop () returns the last element. Element was immediately removed from the list. (The method of square brackets around the i indicates that the parameter is optional, not that you should type square brackets, you will often see this notation in Python Library Reference.)
list.clear () Remove all items in the list, equal to del a [:].
list.index (x) Returns the index of the list with a value of x in the first element. If no matching element will return an error.
list.count (x) Returns the number of times x appears in the list.
list.sort () Of the elements in the list to be sorted.
list.reverse () Inverted elements in the list.
list.copy () Returns a shallow copy of the list is equal to a [:].

The following example illustrates most of the methods 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: Similar to insert, remove or modify the list method sort, etc. no return value.


Use the list as a stack

The method of making a list of lists can easily be used as a stack, the stack as a specific data structure, the first to enter the last element to be released (LIFO). Use append () method can add an element to the top of the stack. Without an explicit index of pop () method can retrieve an item from the top of the stack. 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

The list can also be used as a queue, the queue is the first to join the elements, the first taken out; however, take this list as the purpose is not efficient. Add at the end of the list or pop-up elements of speed, however, to insert or eject from the head speed is not fast (because all the other elements have to move one by one) in the list.

>>> 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 concise way to create lists from the sequence. Some applications will generally be applied to each element of a sequence of operations, with the result which is obtained as the elements to generate a new list, or create sequences determined according to determination conditions.

Each list comprehension are after for with an expression, then zero or more for or if clauses. The result is a list generated from the subsequent context for and if according to the expression. If you want the formula of a tuple, you must use parentheses.

Here we will list each number by three, to get a new list:

>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]

Now we play little tricks:

>>> [[x, x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]

Here we invoke a method individually for each element in a 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 on cycling and other skills:

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

Python lists can also be nested.

The following example shows the 3X4 matrix list:

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

The following example lists 3X4 matrix to 4X3 conversion 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 also can use 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 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

You can use the del statement by index instead of value to remove an element from a list. This is the use of pop () returns a different value. You can use the del statement to remove a cut from the list, or clear the entire list (our previous method of presentation is assigned a cut to the empty list). 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 the instance variable with del:

>>> del a

Tuples and sequences

Tuple number of comma-separated values ​​consists, 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 see, on output tuples are alway enclosed in parentheses, in order to properly express the nested structure. There may be no brackets or when entering, but the brackets are usually required (if the tuple is part of a larger expression).


set

A collection is an unordered collection of unique elements. Basic features include testing and eliminating duplicate elements.

You can create a set of braces ({}). Note: If you want to create an empty set, you must use the set () instead of {}; which creates an empty dictionary, the next section we will introduce this data structure.

The following is a simple demonstration:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # 删除重复的
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # 检测成员
True
>>> 'crabgrass' in basket
False

>>> # 以下演示了两个集合的操作
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # a 中唯一的字母
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # 在 a 中的字母,但不在 b 中
{'r', 'd', 'b'}
>>> a | b                              # 在 a 或 b 中的字母
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # 在 a 和 b 中都有的字母
{'a', 'c'}
>>> a ^ b                              # 在 a 或 b 中的字母,但不同时在 a 和 b 中
{'r', 'd', 'b', 'm', 'z', 'l'}

Collection also support the derivation of the formula:

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

dictionary

Another useful data type built into Python is the dictionary.

A continuous sequence of integer index, and this difference is, keyword dictionary indexed keywords can be any immutable type, usually with a string or numeric.

The best way to understand it as a dictionary are unordered key => value pairs. In the same dictionary, the keys must be different from each other.

A pair of braces creates an empty dictionary: {}.

This is a simple example of the use of a dictionary:

>>> 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 () to build the dictionary directly from the key-tuple list. If you have a fixed pattern, list comprehensions specify a particular key-value pairs:

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

In addition, the dictionary can be used to create an expression to derive any dictionary of keys and values:

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

If the keyword is simply a string of key-value pairs using keyword arguments sometimes more convenient to specify:

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

Traversal techniques

When traversing in the dictionaries, the key and corresponding value can use the items () method for simultaneous interpretation out:

>>> 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 position index and corresponding value can be used enumerate () function also receive:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

While traversing two or more sequences, you can use the zip () in 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 reverse sequence, first specify the sequence, and then call reversesd () function:

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

Traversing a sequence according to the order, the use of sorted () function returns a sorted sequence, does 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 the documentation