common data structure to explain the python


A: sequence

    Mathematically, the sequence is in a row of objects, and in python, the sequence is the most basic data structure. Its main feature to have indexes, each element is iterable. Can be indexed, sliced, add, multiply, and other members of the inspection operations. In python, there are six built-in index, but is commonly used lists, tuples, strings, the following are introduced.

1. List

    Definition: list is required to encapsulate the data type, structure similar language c. And the list is dynamically variable.


    The basic method of operation:


    COUNT (): the number of times an element statistics appear in the list.

    index (): find the index position of the first occurrence of a value from the list.

    append (): add new objects in the end of the list.

    extend (): a plurality of additional one-time value of the other end of the list in sequence.

    insert (): Insert a list of objects in the specified location.

    pop (): the value of the removal of one element of the list (the default last element), and returns the element.

    remove (): remove the first match a list of values.

    reverse (): Reverse the element in the list, the list is not a re-copy.

    reversed (): the elements of the list reverse, a re-copy list.

    sort (): the elements of the sorted list, a list is not re-copy.

    sortd (): the elements of the sorted list, a list of re-copy.

    Copy () : shallow copy, but the original list to affix a new label for a complex object's children will not be fully replicated, if there is a sub-list, change the original value, a new copy of the object will change.

    deepcopy (): deep copy, one copy each complex object out of a single individual. That is, a complete copy.


2. tuple

    Definition: tuples are immutable, and sometimes can be seen as an immutable list. However tuple may be combined with the connection sections, and only a list containing a value, must be used "," job.


    The basic method of operation:


    del: delete tuples.


3. String

    Python string is the most commonly used data types. You can create a pair of quotation marks.


    Basic operations:


    the format (): format string.

4. General Operation Sequence



    index: the index, either, can start from zero from the last position.

    [:]: Slice, used to access a range of elements.

    Common arithmetic operators: the same type of sequence can be arithmetic or replicating sequences.

    in: members of the operator, for checking member (i.e., element) of a sequence whether an object (or other type).

    len, max, min: built-in function len, max and min can return the number of elements contained in the sequence, the maximum and minimum elements.

5. Dictionary

    Definition: The dictionary is mapped, based on the principles of the hash table, the name of the mapping of elements called key. Dictionary (also known as hash table) is the only Python built-in mapping types. Key elements of the dictionary can be any object, but the object must be immutable. For example the sequence set and a list of other mutable objects, not as a dictionary key.


    Basic Operation:


    Clear (): empty dictionary.

    pop (): removing the key, and returns the value corresponding to this key.

    copy (): Copy the dictionary, only one copy (shallow copy).

    update (DD): The DD incorporated into the dictionary D, if the same key, the value of this key is taken as the new value of the value DD.

    get (key, default): Returns the value of the key corresponding to the key, if the value does not exist, default is returned.

    keys (): Returns a collection of objects iteration dictionary keys.

    values (): Returns a collection of dictionary objects iteration values.

    items (): Returns a collection of objects iteration dictionary key-value pairs.

6. collection

    Definition: set by the sequence (or other objects iteration) configuration, is an unordered sequence of elements will not be repeated.


    Basic Operation:


    frozenset (): Creates an empty set of objects is fixed.

    frozenset (iterable): create a new fixed set of objects with iterables.

    set (): Create an empty collection object (can not be used to create an empty set {}).

    set (iterable): create a new set of objects with iterables.

    add (e): Add a new element e in the set; if the element already present, is not added.

    remove (e): a delete from the collection element, if the element does not exist in the collection, a KeyError error will be generated.

    discard (e): removing one element e from the set S, the element does nothing when e is not present.

    clear (): Clear all the elements within the collection.

    copy (): a shallow copy of the collection.

    pop (): Delete a random element from the set S; if this set is empty, then the initiator KeyError exception.

    update (s2): update the dictionary.


II: advanced data structures

    python and some advanced data structures, these data structures is useful when performing arithmetic operations. Here to explain.

1. Stack

    Definition: the stack is a linear table, insert and delete data only from one end of the stack insertion and deletion only in the stack. There are two types of storage stack, i.e., stored and linked linear memory (linked list). So every time deletion of elements is the last element into the stack, so the stack is also known as last in, first out (LIFO) table. Each stack has a stack pointer to its original value of -1, and always points to the last element of the stack.
    Stack handled in two ways, i.e., push (push) and popped (POP), a variable need only move into the stack memory space, the time complexity is O (1); but for two cases out of the stack, the stack when full, the time complexity is also O (1), but when the stack is full, reallocate memory, and moves all the data in the stack, so in this case the time complexity is O (n-) .


    python in the stack: the python, the stack can in fact be achieved with a more simple lists, the elements were increased at the end of the operation with the append, delete operations with elements of pop.

    A list of simple realization:

stack = []
# 向栈顶插入元素
stack.append(1)
stack.append(2)
stack.append(3)
# 删除栈顶的元素
print(stack.pop())
print(stack.pop())
print(stack.pop())

    General ways:

class MyStack(object):
    def __init__(self):
        self.stack_list = []    # 自定义一个列表
        self.count = 0          # 创建一个计数器,模拟栈顶指针

    # 创建一个栈
    def create_one_stack(self):
        return self.stack_list

    # 在栈顶添加元素
    def push(self, value):
        self.stack_list.insert(0,value)
        self.count += 1         # 计数器加一

    # 删除栈顶元素
    def pop(self):
        self.stack_list.pop(0)
        self.count -= 1         # # 计数器减一

    # 返回栈顶元素值
    def stack_num(self):
        if self.count:
            return self.stack_list[0]

    #打印栈内容
    def show_all(self):
        for s in self.stack_list:
            print(s)

if __name__ == '__main__':
    m = MyStack()
    m.create_one_stack()
    # 增加栈顶元素
    m.push(1)
    m.push(2)
    m.push(3)
    print('栈顶元素为:',m.stack_num())
    print('之前的元素为:')
    m.show_all()
    # 删除栈顶元素
    m.pop()
    print('之后的元素为:')
    m.show_all()

2. Queue

    Definition: A queue is a special linear form, and the like stacks, but the delete operation permission table in front of, and behind the insertion operation table, the table is also a restricted linear operation. Referred to as the tail end of the end, delete operation will be referred to as head-of-insertion operation. Into the queues and circular queue . Here to discuss the queues.

    Normal queue implementation:

class Queue(object):
    def __init__(self):
        self.__list = []    # 创建一个列表

    def inQueue(self,item):
        # 从队尾入队,从队头出队
        self.__list.append(item)

    def outQueue(self):
        # 从队头出队
        return self.__list.pop(0)

if __name__ == '__main__':
    m = Queue()
    # 从队头入队
    m.inQueue(1)
    m.inQueue(2)
    # 从队尾出队
    print(m.outQueue())
    print(m.outQueue())

    Deque implemented:

class Queue(object):
    def __init__(self):
        self.__list = []    # 创建一个列表

    def add_Front(self,x):
        #在列表头部添加
        self.__list.insert(0,x)

    def add_End(self,x):
        #在队列尾部添加元素
        self.__list.append(x)

    def pop_Front(self):
        #在头部删除元素
        return self.__list.pop(0)

    def pop_End(self):
        #在尾部删除元素
        return self.__list.pop()


if __name__ == '__main__':
    m = Queue()
    # 在队列头部添加元素
    m.add_Front(1)
    m.add_Front(2)
    m.add_Front(3)
    m.add_Front(4)
    # 在队列尾部添加元素
    m.add_End(5)
    m.add_End(6)
    m.add_End(7)
    m.add_End(8)
    # 在列表头部和尾部删除元素
    print(m.pop_Front())
    print(m.pop_Front())
    print(m.pop_End())
    print(m.pop_End())

    These are the python knowledge commonly used data structures, as well as other less commonly used data structures and algorithms, but often combined to achieve a multiplier effect, after these data structures will be to show.

    If you enjoyed this article, may wish to point praise, or click a reward function on the right, a lot of support, thank you, I hope you slowly discover the beauty and joy in marine technology inside.

Guess you like

Origin www.cnblogs.com/ITXiaoAng/p/11581396.html