Python - Data structure - the fifteenth day

Python data structures

This chapter is mainly combined with our knowledge 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) Adding an element to the end of the list, corresponding to a [len (a):] = [x].
list.extend(L) To expand the list by adding all of the elements specified list, corresponding to a [len (a):] = L.
list.insert(i, x) Insert an element at the specified location. The first parameter is the index to be inserted into the front of which that element, e.g. a.insert (0, x) will be inserted before the entire list, and a.insert (len (a), x) corresponds a.append ( x).
list.remove(x) Remove the first element in the list whose value is x. If no such element, it returns an error.
list.pop([i]) Removes the element from the specified position in this list, and returns it. If you do not specify the index, a.pop () Returns the last element. Then elements are removed from the list. (I approach the square brackets denote that the parameter is optional, not that you should type square brackets, you will see this notation frequently in the Python Library Reference.)
list.clear() Remove all items in the list, equal to del a [:].
list.index(x) Returns the index of the first value in the list of elements x. If the element does not match the returns an error.
list.count(x) Returns the number of times x appears in the list.
list.sort() In the list of elements to be sorted.
list.reverse() The list of elements inverted.
list.copy() Back shallow copy of a list, is equal to a [:].

The following example demonstrates most of the methods list:

Examples

>>> 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, modify, or remove list sort method returns no value.


Use the list as a stack

List listing such method can be easily used as a stack, the stack as the specific data, where the first element is the last release ( LIFO ). It can be added with the append () method to a top of the stack element. Without an explicit index pop () method of an element can be released from the top of the stack . E.g:

Examples

>>> 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 may also be used as a queue, but added in the first queue element, is taken out first; however such as to take the list of objects is not efficient. At the end of the list or add pop elements fast speed, but insert or eject from the head speed is not fast (one by one to move because all other elements had) in the list.

Examples

>>> 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 a list from the sequence. Typically some application operation to each element of a sequence, with the results obtained as an element which generates a new list, or create a sub-sequence is determined according to the determination condition.

Each list comprehensions are after for with an expression, then zero or more for or if clauses. The result is out of a list generated for subsequent contexts and if based on the expression. If you want to derive a tuple expression, 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]]

We call this sequence where each element one by one method:

Examples

>>> 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 demonstrations of recycling and other tips:

>>> 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 complex expressions may be used to derive the formula 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 list of examples of the transformation matrix is ​​4X3 3X4 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 may 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

According to the del statement to remove the index, rather than the value of an element from a list . This use pop () returns a value different. Can use the del statement removes a cut from the list, or clear the entire list (our previous method of presentation is assigned to the cutting an 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 variables entities del:

>>> del a

Tuples and sequences

Separated by a number of tuple values commas , 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, the output tuples are always enclosed in parentheses, in order to properly nested tuples. There may be no brackets or when you enter, but the brackets is often necessary (if the tuple is part of a larger expression).


set

Collection is a set of unordered elements will not be repeated. Basic features include testing and eliminating duplicate elements.

Can be created using a set of braces ({}). Note: If you want to create an empty set, you must 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) to delete duplicate #
{ 'orange', 'banana' , 'PEAR', 'Apple'}
>>> 'Orange' in the detection member Basket #
True
>>> 'crabgrass' in Basket
False

>>> # the following illustrates the operation of the two sets
...
>>> sET a = ( 'Abracadabra')
>>> B = SET ( 'alacazam')
>>> # a a only letters
{ 'a', 'R & lt', 'B', 'C', 'D'}
>>> a - b # in the letters a, b, but not
{ 'R & lt', 'D', 'b'}
>>> a | b # in the letter a or b
{ 'a', 'c' , 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # a and b are in the letter
{ 'a', 'C'}
>>> a # b ^ a or b in the letters, but not both a and b in
{ ' r ',' d ',' b ',' m ',' z ',' l '}

Collection also supports the derivation 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.

Sequences, which are integer indexes, and this difference is, the index dictionary keyword, keywords can be any immutable type, usually a string or numeric.

BEST MODE dictionary is to be understood as an 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

Dict constructor () to build a list of tuples dictionaries directly from the key. If there is a fixed pattern, to derive a list of key-value pairs specifying certain:

>>> 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 just a simple string, use the keyword parameter specifies the key sometimes more convenient to:

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

Traversal techniques

When traversing in the dictionary, and the corresponding keyword values ​​can be items () method of simultaneously deciphered:

>>> 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 the corresponding values ​​can be the enumerate () function is obtained simultaneously:

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

Simultaneously traverse two or more sequences, using zip () a combination of:

>>> 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 the reversed () function:

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

Traversing a sequence according to the order, using the 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

Refer to the documentation

Guess you like

Origin www.cnblogs.com/jeremywucnblog/p/11648994.html