Detailed and implementation of Python list

Source: Internet
Author: User
Tags python list
The list is a common data type in Python that is built into Python and inherits from object. Next, a comprehensive introduction to the list of common methods and their own implementation of the class list function of the class Create a list

Create an empty list

List1 = []

List2 = List ()

Create and initialize the list

List1 = [' A ', ' B ', ' C ', 123] #比较常用, types can be inconsistent

List2 = List (List1) #传入的为可迭代对象, such as Set,tuple,generator

LIST3 = [I for I in range (10)] # List Builder

LIST4 = [x for x in range (ten) if x 2 = 0] # generate even

LIST5 = [0] * 5 # Generate [0, 0, 0, 0, 0] common methods

Append

Append (p_object) adds data to the end of the list

List1 = []

List1.append (' 456 ')

Len

Len (list1) # Returns the number of elements in List1

Insert

Insert (index, p_object) inserts data into the list at the specified location (index)

List1.insert (3, ' abc ') # when index is greater than or equal to list length, insert to end

List1.insert ( -2, ' abc ') # is a negative number from the back forward when index < Len (list1) *-1, then insert data pops in the header

POPs (Index=none) pops up data at the specified location (index), throws an exception when index >= len (list1) or index < Len (list1) * 1

List1.pop (1)

List1.pop () #弹出末尾数据Remove

Remove (value) removes the specified element from the list, throws an exception if the list is empty or if the specified element does not exist in the list

List1.remove (' abc ')

Clear

List Empty index

Index (value, Start=none, Stop=none) find the specified element sort

Sort the elements in a list count

The number of occurrences of the Count element (value), and the more complex statistical recommendations are statistically recommended through the From collections import Counter extend

Extend (iterable) expands the list

After adding content to List1 in Ist1.extend (list2) # Lis2, you can also use List1 + list2 Reverse

Reverse the list data

List.reverse () # from [' A ', ' B ', ' C '] into [' C ', ' B ', ' A '] copy

Copy the original list and generate a new list traversal

  
    List1 = [x for x in range (0,10,2)]
    for I in range (len (list1)):  print (list1[i], end= ")
    PR int () for
    x in List1:  print (x, end= ')
    print () to
    Ind,value in Enumerate (list1): 
  
     print (Ind, value, sep= ' = ', end = ')
  
Find

The search for list mainly uses sliced slices (slice)

Slice is a built-in function in Python

S1 = Slice (0,1) #[0:1] starting from 0, 1 ends (excluding)

S2 = Slice (4) #[0:4]

S3 = Slice (0,10,2) #[0:10:2], starting from 0, 10 ends, one value per fetch

List1 = [x for x in range (10)]

LIST1[S1]

List1[0:10:2]

list1[::] #查询所有元素

LIST1[5] #取下标为5的数 passed in int type

List1[-5:-2] #也可以取负数Implement list class

This is implemented by a linked list. LinkedList contains attributes and node classes such as Size,start,end, where size represents the number of node nodes, start is the starting node, and end is the ending node. The node class contains the Pre,next,data attribute, the value of the pre is the previous node node, and next is the latter, and the data is placed in the information

  
    #!/usr/bin Python3 #-*-coding:utf-8-*-    class LinkedList (object):       Node class     class __node (object):         def __init__ (self, data, pre, next) :             Self.pre = pre     # forward node             Self.next = Next   # back node             Self.data = data   # &NBSP
   ;
       # Initialize size, start, end node properties     def __init__ (self):         self.__size = 0         Self.__start = None         Self.__end = None       # Add data     DEF append (self, data):         Last_node = self.__end         node = self.__node (data, Last_node, None)         If self.__size = 0: &N Bsp          Self.__start = node         ELSE:           &NBS  P
   Last_node.next = node         Self.__end = node         Self.__size + 1       # Insert data     DEF insert (self, Index, data):         if Inde x >= self.__size: # End Add             self.append (data)       &NBSP ;     return         ELIF index <= self.__size *-1 or index = = 0:   # start Add &N Bsp           Next_node = Self.__start             node = Self.__n Ode (data, None, Next_node)             NEXT_NODE.PRE = node       &NBS P     Self.__start = node         ELSE: # middle Add         &NB  Sp Next_node = Self.__get_node (index)             Pre_node = next_node.pre     &NBS P       node = self.__node (data, Pre_node, Next_node)             Pre_node . Next = node             NEXT_NODE.PRE = node         Self.__siz E + 1       # pop-up data     def pop (self, index=none):         IF Index is None:             index = self.__size-1         if SE lf.__size = 0:             raise Indexerror (' Pop from empty list ')     &NB Sp   If index >= self.__size or index < Self.__size *-1:             raise Ind Exerror (' Pop index out of range ')         Pop_node = Self.__get_node (index)     &NBSP ;   Pre_nodE = pop_node.pre         Next_node = pop_node.next         if Pre_node is None: # Pop-up for opening node             Next_node.pre = None         &NBSP ;   Self.__start = next_node             Pop_node.next = None     &NBSP ;   Elif Next_node is None: # Pop-up for end node             Pre_node.next = none             Self.__end = pre_node             Pop_node.pre = Non  E         ELSE:             Pop_node.pre = None     
           Pop_node.next = None             Pre_node.next = Next_node
               Next_node.pre = pre_node         self.__size-= 1     &nbsp  # delete elements     def remove (self, obj):         pos = None          For IND, value in Enumerate (self):             If value = obj:                  POS = ind                 break       &AMP;NBS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.