欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python列表操作实例

程序员文章站 2023-11-20 12:41:58
本文实例讲述了python列表操作的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:class node:    """si...

本文实例讲述了python列表操作的方法。分享给大家供大家参考。

具体实现方法如下:

复制代码 代码如下:
class node:
   """single node in a data structure"""
 
   def __init__(self, data):
      """node constructor"""
      
      self._data = data
      self._nextnode = none
    
   def __str__(self):
      """node data representation"""
 
      return str(self._data)    
 
class list:
   """linked list"""
 
   def __init__(self):
      """list constructor"""
 
      self._firstnode = none
      self._lastnode = none
 
   def __str__(self):
      """list string representation"""
 
      if self.isempty():
         return "empty"
 
      currentnode = self._firstnode
      output = []
 
      while currentnode is not none:
         output.append(str(currentnode._data))
         currentnode = currentnode._nextnode
 
      return " ".join(output)    
 
   def insertatfront(self, value):
      """insert node at front of list"""
 
      newnode = node(value)
 
      if self.isempty():  # list is empty
         self._firstnode = self._lastnode = newnode
      else:   # list is not empty
         newnode._nextnode = self._firstnode
         self._firstnode = newnode
        
   def insertatback(self, value):
      """insert node at back of list"""
 
      newnode = node(value)
 
      if self.isempty():  # list is empty
         self._firstnode = self._lastnode = newnode
      else:  # list is not empty
         self._lastnode._nextnode = newnode
         self._lastnode = newnode
 
   def removefromfront(self):
      """delete node from front of list"""
 
      if self.isempty():  # raise exception on empty list
         raise indexerror, "remove from empty list"
 
      tempnode = self._firstnode
 
      if self._firstnode is self._lastnode:  # one node in list
         self._firstnode = self._lastnode = none
      else:
         self._firstnode = self._firstnode._nextnode
 
      return tempnode
 
   def removefromback(self):
      """delete node from back of list"""
 
      if self.isempty():  # raise exception on empty list
         raise indexerror, "remove from empty list"
     
      tempnode = self._lastnode
 
      if self._firstnode is self._lastnode:  # one node in list
         self._firstnode = self._lastnode = none
      else:
         currentnode = self._firstnode
 
         # locate second-to-last node
         while currentnode._nextnode is not self._lastnode:
               currentnode = currentnode._nextnode
               
         currentnode._nextnode = none
         self._lastnode = currentnode
 
      return tempnode
    
   def isempty(self):
      """returns true if list is empty"""
 
      return self._firstnode is none

希望本文所述对大家的python程序设计有所帮助。