Python study notes (seven) -------- Python data structures

First, the relevant

The data structure is a computer to store, organize the data mode. Data structure refers to the presence of one or more specific mutual relationship between data elements set.

Most of the data structure in Python may ultimately broken down into three types: set (Set), the sequence (Sequence), mapping (Mapping).

1, is a collection of independent scalar sequence and mapping special data structure, which supports a variety of mathematical set theory operation. Its existence makes the application code to achieve mathematical theory becomes easy.

2, Python sequence is the most basic built-in types. It is divided into seven types: list, string, a tuple, Unicode strings, byte array buffer and xrange objects. Commonly used are: a list (List), string (String), tuples (Tuple).

3, the mapping is implemented in Python data structure dictionary (Dictionary). As a third basic unit, flexible mapping makes it have a wide range of applications and excellent scalability in a variety of occasions.

Second, the common Python data structures

1. List: list

We put on a list to illustrate his first, because the list of strings or tuples different, lists are mutable. For "variable" and "immutable" The students have questions, you can view the " Python study notes (six) -------- Python function ," the article detailed description of the variable and non-variable there.

Python list of related methods

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 [:].

 practice

myList = [1, "Baldwin", (1, 2, 4), {"Jack", "Tom"}, {"money": 40}]
newList = [43]

myList.append({"age": 18})              # 给当前列表新增一个元素
print(myList)

myList.extend(newList)                  # 通过制定列表来扩充当前列表
print(myList)

myList.insert(1, {"name": "Baldwin"})   # 在下表1的位置上插入
print(myList)

myList.remove(1)                        # 移除值为1的元素
print(myList)

print(myList.pop(3))                    # 移除指定位置元素,并返回这个元素值

myList.clear()                          # 删除所有元素
print(myList)
E:\WorkSpaces\PycharmProjects\PyDemo\venv\Scripts\python.exe E:/WorkSpaces/PycharmProjects/PyDemo/cn/yzstu/__init__.py
[1, 'Baldwin', (1, 2, 4), {'Jack', 'Tom'}, {'money': 40}, {'age': 18}]
[1, 'Baldwin', (1, 2, 4), {'Jack', 'Tom'}, {'money': 40}, {'age': 18}, 43]
[1, {'name': 'Baldwin'}, 'Baldwin', (1, 2, 4), {'Jack', 'Tom'}, {'money': 40}, {'age': 18}, 43]
[{'name': 'Baldwin'}, 'Baldwin', (1, 2, 4), {'Jack', 'Tom'}, {'money': 40}, {'age': 18}, 43]
{'Jack', 'Tom'}
[]

Process finished with exit code 0

More use of the list of forms in Python, sometimes based on the list to implement a stack or queue

list implementation of a stack

Heap stack is a data structure. Data structure of a data item that is stacked in sequence, only one end (referred to as a top of the stack (Top)) to insert and delete data items (last out), data can be understood as access to the stack bucket put the book and pick up the book.

list implementation of a stack structure mainly relying append method and pop methods, apend method no longer tired, we look at pop special use of the method: If no index, a.pop () Returns the last element . Relying on these two methods can be achieved stack data structure requirements.

stack = [1, 2, 3, 4, 5]

stack.append(6)     #压栈
print(stack)
stack.pop()         #出栈
print(stack)
E:\WorkSpaces\PycharmProjects\PyDemo\venv\Scripts\python.exe E:/WorkSpaces/PycharmProjects/PyDemo/cn/yzstu/__init__.py
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]

Process finished with exit code 0

list queue

A queue is a special linear form , is special in that it only allows deletion at the front end of the table (Front), while the rear end of insertion, the table (REAR), and stack as a queue by the operating linear restriction table. Referred to as the tail end of the end, delete operation will be referred to as head-of-insertion operation. Queue data access rules can be said Jane as a "first in first out FIFO", can be understood as line up on the train, people must be the first line of the first to get on the train.

Realize there are some problems with the queue list, add, or pop-up data in the end of the list is very fast, but data to be inserted in the head behind the song all the data needed to move, apparently so efficiency is very low.

At the head of the pop-up list function is not used directly, we are here to introduce deque

from collections import deque
list = [1,2,3,4,5]
queue = deque(list)


print(queue.popleft())      # 出队
print(queue)
queue.append(18)            # 入队
print(queue)
E:\WorkSpaces\PycharmProjects\PyDemo\venv\Scripts\python.exe E:/WorkSpaces/PycharmProjects/PyDemo/cn/yzstu/__init__.py
1
deque([2, 3, 4, 5])
deque([2, 3, 4, 5, 18])

Process finished with exit code 0

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.

myList = [1, 23, 87, 5]

newList = [2 * m + 1 for m in myList]
print(newList)
E:\WorkSpaces\PycharmProjects\PyDemo\venv\Scripts\python.exe E:/WorkSpaces/PycharmProjects/PyDemo/cn/yzstu/__init__.py
[3, 47, 175, 11]

Process finished with exit code 0

Above demonstrates a simple list comprehensions, list there are many interesting uses derivation, interested students can go try.

2. tuple

Tuple composed of a plurality of values ​​separated by commas.

myTuple = (12, 78, 45, 656)     # 常规方式定义元组
newTuple = 12, 11, 10           # 特殊方式 

print(myTuple)
print(newTuple)
E:\WorkSpaces\PycharmProjects\PyDemo\venv\Scripts\python.exe E:/WorkSpaces/PycharmProjects/PyDemo/cn/yzstu/__init__.py
(12, 78, 45, 656)
(12, 11, 10)

Process finished with exit code 0

Tuples can be created two ways to go, but the output will be put in brackets, in this suggestion to create using conventional methods

3. collection

Is a set containing the elements do not overlap and no data structure, in Python, having a collection function testing and eliminating duplicate elements.

mySet = {1231, 3123, 31231, 1212, 1212}
newSet = {m-1000 for m in mySet}

print(mySet)
print(newSet)
E:\WorkSpaces\PycharmProjects\PyDemo\venv\Scripts\python.exe E:/WorkSpaces/PycharmProjects/PyDemo/cn/yzstu/__init__.py
{3123, 1212, 31231, 1231}
{231, 2123, 212, 30231}

Process finished with exit code 0

The above program is running, we can get three pieces of information:

1 by a set of braces {} Create

2. observe, create a collection when I entered two duplicate values ​​(the last two), although the set not being given, but automatically removes duplicate values

3. The set also supports derivations

4. Dictionary

The Python dictionary reference map in the Java type, a double row random data set, the data stored in the form of key-value pairs, often take the string or value as a key in a dictionary, the key can not be repeated, but the value of It can be repeated. When the value may be a value by key

{} Create a dictionary

myDict = {"name": "Baldwin", "age": 18}
print(myDict["name"])
E:\WorkSpaces\PycharmProjects\PyDemo\venv\Scripts\python.exe E:/WorkSpaces/PycharmProjects/PyDemo/cn/yzstu/__init__.py
Baldwin

Process finished with exit code 0

dict () constructor to create a dictionary

mydict = dict({'name': 'Baldwin', 'age': 18})
print(mydict)

+ Derivations create a dictionary by tuples

mydict = {x:x+11 for x in [1,2,3]}
print(mydict)

Third, the summary

Various data structures remain the same language, learn one another almost

 

Published 46 original articles · won praise 113 · views 110 000 +

Guess you like

Origin blog.csdn.net/shouchenchuan5253/article/details/104964163