python自定義序列類型

序列類型的分類

可以按照兩個維度對序列進行分類
1.根據數據的維度進行區分
            1.容器序列:list 、tuple 、 deque
            2扁平序列 : str 、 bytes、bytearray、array.array
2.序列是否可變進行區分
            1.可變序列:list 、deque、 bytearray、 array
            2,不可變序列:str、tuple、bytes

容器序列是可以放入任意類性的數據。
扁平序列只能是單一的數據類型。

序列的abc繼承關係

from _collections_abc # 使用ctrl+鼠標左鍵 可查看源碼
抽象基類:
Squence
MutableSequence
自定義序列類型需要實現抽象基類當中的魔法函數。

序列當中的+ ,+=和extend的區別


my_list=[]
my_list.append(1)
my_list.append("a")
a=[1,2]
c=a+[3,4]#[1, 2, 3, 4]
#TypeError: can only concatenate list (not "tuple") to list
# d=a+(3,4)
print(c)
#就地加  參數可以是任意序列,
c+=[8,8]
print("...................")
print(c)
c+=(5,6,7,8)
print("....................")
print(c)

a.extend(range(3))#或者任意的可迭代對象
print(a)#[1, 2, 0, 1, 2]
a.append([1,2])
print(a)#[1, 2, 0, 1, 2, [1, 2]]
a.append((7,7))
print(a)#[1, 2, 0, 1, 2, [1, 2], (7, 7)]

運行結果:
H:\ANACONDA\python.exe I:/ainlp/pythonHight/chapter05/sequence_test.py
[1, 2, 3, 4]

[1, 2, 3, 4, 8, 8]

[1, 2, 3, 4, 8, 8, 5, 6, 7, 8]
[1, 2, 0, 1, 2]
[1, 2, 0, 1, 2, [1, 2]]
[1, 2, 0, 1, 2, [1, 2], (7, 7)]

Process finished with exit code 0

實現可切片的對象

列表的切片如下:

#模式[start:end:step]
"""
    其中,第一個數字start表示切片開始位置,默認爲0;
    第二個數字end表示切片截止(但不包含)位置(默認爲列表長度);
    第三個數字step表示切片的步長(默認爲1)。
    當start爲0時可以省略,當end爲列表長度時可以省略,
    當step爲1時可以省略,並且省略步長時可以同時省略最後一個冒號。
    另外,當step爲負整數時,表示反向切片,這時start應該比end的值要大才行。
"""
aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
print (aList[::])  # 返回包含原列表中所有元素的新列表
print (aList[::-1])  # 返回包含原列表中所有元素的逆序列表
print (aList[::2])  # 隔一個取一個,獲取偶數位置的元素
print (aList[1::2])  # 隔一個取一個,獲取奇數位置的元素
print (aList[3:6])  # 指定切片的開始和結束位置
aList[0:100]  # 切片結束位置大於列表長度時,從列表尾部截斷
aList[100:]  # 切片開始位置大於列表長度時,返回空列表

aList[len(aList):] = [9]  # 在列表尾部增加元素
aList[:0] = [1, 2]  # 在列表頭部插入元素
aList[3:3] = [4]  # 在列表中間位置插入元素
aList[:3] = [1, 2]  # 替換列表元素,等號兩邊的列表長度相等
aList[3:] = [4, 5, 6]  # 等號兩邊的列表長度也可以不相等
aList[::2] = [0] * 3  # 隔一個修改一個
print (aList)
aList[::2] = ['a', 'b', 'c']  # 隔一個修改一個
aList[::2] = [1,2]  # 左側切片不連續,等號兩邊列表長度必須相等
aList[:3] = []  # 刪除列表中前3個元素

del aList[:3]  # 切片元素連續
del aList[::2]  # 切片元素不連續,隔一個刪一個

創建可切片對象

手動實現序列類型:

import numbers
#自定義不可修改序列 基於Sequence
class  Group:
    #支持切片
    def __init__(self,group_name,company_name,staffs):
        self.group_name=group_name
        self.company_name=company_name
        self.staffs=staffs

    # 先將序列協議裏面的抽象方法實現
    def __reversed__(self):

        self.staffs.reverse()
    #實際上現在只需要實現__getitem__就可以實現切片了
    def __getitem__(self,item):

        # return self.staffs[item]
        #獲取當前的class
        cls=type(self)  #或者硬編碼爲cls=Group
        if  isinstance(item,slice):
            return cls(group_name=self.group_name,company_name=self.company_name,staffs=self.staffs[item])
        elif isinstance(item,numbers.Integral):
            return cls(group_name=self.group_name,company_name=self.company_name,staffs=[self.staffs[item]])
    def __len__(self):
        return len(self.staffs)

    def __iter__(self):
        return iter(self.staffs)


    def __contains__(self, item):
        if item in self.staffs:
            return True
        else:
            return False

group=Group(company_name="xiaopang",group_name="eater",staffs=["music","book","clothes"])
print(group[:2])
if "music" in group: #這個會調用類裏面的__contains__(self,item)方法
    print("yes")
print("-------------------------------------------")
reversed(group) # 對序列做翻轉操作
for user in group:
    print(user)
print("-----------------------------------------------")

使用 bisect 管理已排序的序列

import bisect
'''
始終幫我們維護一個排序號的序列
'''
#用來處理已排序的序列,用來維持已排序的序列,升序



#二分查找
inter_list=[]
#插入
bisect.insort(inter_list,3)
bisect.insort(inter_list,2)
bisect.insort(inter_list,5)
bisect.insort(inter_list,6)
bisect.insort(inter_list,1)
print(inter_list)
#查找插入的位置
print(bisect.bisect(inter_list,3))  #從相同元素的右面插入 bisect = bisect_right   # backward compatibility
print(bisect.bisect_left(inter_list,3))  #從相同元素的左面插入
print(bisect.bisect_right(inter_list,3))
print(inter_list)
print("-----------------------------------------------------------------")
from collections import deque
inter_list=deque()
bisect.insort(inter_list,3)
bisect.insort(inter_list,2)
bisect.insort(inter_list,5)
bisect.insort(inter_list,6)
bisect.insort(inter_list,1)
print(inter_list)
#查找插入的位置
print(bisect.bisect(inter_list,3))  #從相同元素的右面插入 bisect = bisect_right   # backward compatibility
print(bisect.bisect_left(inter_list,3))  #從相同元素的左面插入
print(bisect.bisect_right(inter_list,3))
print(inter_list)


array,deque

#數組
#array和list的一個重要區別,array只能存放指定的數據類型

import array #array的性能高於list
my_array=array.array(“i”)
my_array.append(2)
print(my_array)
參數類型參考官方網址
https://docs.python.org/3.6/library/array.html
在這裏插入圖片描述
arrayType的源碼


# encoding: utf-8
# module array
# from H:\ANACONDA\lib\site-packages\wordcloud\query_integral_image.cp36-win_amd64.pyd
# by generator 1.147
"""
This module defines an object type which can efficiently represent
an array of basic values: characters, integers, floating point
numbers.  Arrays are sequence types and behave very much like lists,
except that the type of objects stored in them is constrained.
"""
# no imports

# Variables with simple values

typecodes = 'bBuhHiIlLqQfd'

# functions

def _array_reconstructor(*args, **kwargs): # real signature unknown
    """ Internal. Used for pickling support. """
    pass

# classes

class ArrayType(object):
    """
    array(typecode [, initializer]) -> array
    
    Return a new array whose items are restricted by typecode, and
    initialized from the optional initializer value, which must be a list,
    string or iterable over elements of the appropriate type.
    
    Arrays represent basic values and behave very much like lists, except
    the type of objects stored in them is constrained. The type is specified
    at object creation time by using a type code, which is a single character.
    The following type codes are defined:
    
        Type code   C Type             Minimum size in bytes 
        'b'         signed integer     1 
        'B'         unsigned integer   1 
        'u'         Unicode character  2 (see note) 
        'h'         signed integer     2 
        'H'         unsigned integer   2 
        'i'         signed integer     2 
        'I'         unsigned integer   2 
        'l'         signed integer     4 
        'L'         unsigned integer   4 
        'q'         signed integer     8 (see note) 
        'Q'         unsigned integer   8 (see note) 
        'f'         floating point     4 
        'd'         floating point     8 
    
    NOTE: The 'u' typecode corresponds to Python's unicode character. On 
    narrow builds this is 2-bytes on wide builds this is 4-bytes.
    
    NOTE: The 'q' and 'Q' type codes are only available if the platform 
    C compiler used to build Python supports 'long long', or, on Windows, 
    '__int64'.
    
    Methods:
    
    append() -- append a new item to the end of the array
    buffer_info() -- return information giving the current memory info
    byteswap() -- byteswap all the items of the array
    count() -- return number of occurrences of an object
    extend() -- extend array by appending multiple elements from an iterable
    fromfile() -- read items from a file object
    fromlist() -- append items from the list
    frombytes() -- append items from the string
    index() -- return index of first occurrence of an object
    insert() -- insert a new item into the array at a provided position
    pop() -- remove and return item (default last)
    remove() -- remove first occurrence of an object
    reverse() -- reverse the order of the items in the array
    tofile() -- write all items to a file object
    tolist() -- return the array converted to an ordinary list
    tobytes() -- return the array converted to a string
    
    Attributes:
    
    typecode -- the typecode character used to create the array
    itemsize -- the length in bytes of one array item
    """
    def append(self, *args, **kwargs): # real signature unknown
        """ Append new value v to the end of the array. """
        pass

    def buffer_info(self, *args, **kwargs): # real signature unknown
        """
        Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
        
        The length should be multiplied by the itemsize attribute to calculate
        the buffer length in bytes.
        """
        pass

    def byteswap(self, *args, **kwargs): # real signature unknown
        """
        Byteswap all items of the array.
        
        If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
        raised.
        """
        pass

    def count(self, *args, **kwargs): # real signature unknown
        """ Return number of occurrences of v in the array. """
        pass

    def extend(self, *args, **kwargs): # real signature unknown
        """ Append items to the end of the array. """
        pass

    def frombytes(self, *args, **kwargs): # real signature unknown
        """ Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method). """
        pass

    def fromfile(self, *args, **kwargs): # real signature unknown
        """ Read n objects from the file object f and append them to the end of the array. """
        pass

    def fromlist(self, *args, **kwargs): # real signature unknown
        """ Append items to array from list. """
        pass

    def fromstring(self, *args, **kwargs): # real signature unknown
        """
        Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method).
        
        This method is deprecated. Use frombytes instead.
        """
        pass

    def fromunicode(self, *args, **kwargs): # real signature unknown
        """
        Extends this array with data from the unicode string ustr.
        
        The array must be a unicode type array; otherwise a ValueError is raised.
        Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
        some other type.
        """
        pass

    def index(self, *args, **kwargs): # real signature unknown
        """ Return index of first occurrence of v in the array. """
        pass

    def insert(self, *args, **kwargs): # real signature unknown
        """ Insert a new item v into the array before position i. """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """
        Return the i-th element and delete it from the array.
        
        i defaults to -1.
        """
        pass

    def remove(self, *args, **kwargs): # real signature unknown
        """ Remove the first occurrence of v in the array. """
        pass

    def reverse(self, *args, **kwargs): # real signature unknown
        """ Reverse the order of the items in the array. """
        pass

    def tobytes(self, *args, **kwargs): # real signature unknown
        """ Convert the array to an array of machine values and return the bytes representation. """
        pass

    def tofile(self, *args, **kwargs): # real signature unknown
        """ Write all items (as machine values) to the file object f. """
        pass

    def tolist(self, *args, **kwargs): # real signature unknown
        """ Convert array to an ordinary list with the same items. """
        pass

    def tostring(self, *args, **kwargs): # real signature unknown
        """
        Convert the array to an array of machine values and return the bytes representation.
        
        This method is deprecated. Use tobytes instead.
        """
        pass

    def tounicode(self, *args, **kwargs): # real signature unknown
        """
        Extends this array with data from the unicode string ustr.
        
        Convert the array to a unicode string.  The array must be a unicode type array;
        otherwise a ValueError is raised.  Use array.tobytes().decode() to obtain a
        unicode string from an array of some other type.
        """
        pass

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass

    def __copy__(self, *args, **kwargs): # real signature unknown
        """ Return a copy of the array. """
        pass

    def __deepcopy__(self, *args, **kwargs): # real signature unknown
        """ Return a copy of the array. """
        pass

    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __iadd__(self, *args, **kwargs): # real signature unknown
        """ Implement self+=value. """
        pass

    def __imul__(self, *args, **kwargs): # real signature unknown
        """ Implement self*=value. """
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __reduce_ex__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

    def __sizeof__(self, *args, **kwargs): # real signature unknown
        """ Size of the array in memory, in bytes. """
        pass

    itemsize = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the size, in bytes, of one array item"""

    typecode = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """the typecode character used to create the array"""


    __hash__ = None


array = ArrayType


class __loader__(object):
    """
    Meta path import for built-in modules.
    
        All methods are either class or static methods to avoid the need to
        instantiate the class.
    """
    @classmethod
    def create_module(cls, *args, **kwargs): # real signature unknown
        """ Create a built-in module """
        pass

    @classmethod
    def exec_module(cls, *args, **kwargs): # real signature unknown
        """ Exec a built-in module """
        pass

    @classmethod
    def find_module(cls, *args, **kwargs): # real signature unknown
        """
        Find the built-in module.
        
                If 'path' is ever specified then the search is considered a failure.
        
                This method is deprecated.  Use find_spec() instead.
        """
        pass

    @classmethod
    def find_spec(cls, *args, **kwargs): # real signature unknown
        pass

    @classmethod
    def get_code(cls, *args, **kwargs): # real signature unknown
        """ Return None as built-in modules do not have code objects. """
        pass

    @classmethod
    def get_source(cls, *args, **kwargs): # real signature unknown
        """ Return None as built-in modules do not have source code. """
        pass

    @classmethod
    def is_package(cls, *args, **kwargs): # real signature unknown
        """ Return False as built-in modules are never packages. """
        pass

    @classmethod
    def load_module(cls, *args, **kwargs): # real signature unknown
        """
        Load the specified module into sys.modules and return it.
        
            This method is deprecated.  Use loader.exec_module instead.
        """
        pass

    def module_repr(module): # reliably restored by inspect
        """
        Return repr for the module.
        
                The method is deprecated.  The import machinery does the job itself.
        """
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """list of weak references to the object (if defined)"""


    __dict__ = None # (!) real value is "mappingproxy({'__module__': '_frozen_importlib', '__doc__': 'Meta path import for built-in modules.\\n\\n    All methods are either class or static methods to avoid the need to\\n    instantiate the class.\\n\\n    ', 'module_repr': <staticmethod object at 0x00000000023C6198>, 'find_spec': <classmethod object at 0x00000000023C61D0>, 'find_module': <classmethod object at 0x00000000023C6208>, 'create_module': <classmethod object at 0x00000000023C6240>, 'exec_module': <classmethod object at 0x00000000023C6278>, 'get_code': <classmethod object at 0x00000000023C62E8>, 'get_source': <classmethod object at 0x00000000023C6358>, 'is_package': <classmethod object at 0x00000000023C63C8>, 'load_module': <classmethod object at 0x00000000023C6400>, '__dict__': <attribute '__dict__' of 'BuiltinImporter' objects>, '__weakref__': <attribute '__weakref__' of 'BuiltinImporter' objects>})"


# variables with complex values

__spec__ = None # (!) real value is "ModuleSpec(name='array', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in')"


列表推導式(列表生成式),生成器表達式,字典推導式



#列表生成式(列表推導式)高於列表操作
#1.提出1到20之間的奇數
odd_list=[]
for i in range(21):
    if i%2==1:
        odd_list.append(i)
print(odd_list)
print("------------------------------------------")
list1=[i for i in range(21) if i%2==1]
print(list1)
print(type(list1))
print("-----------------------------------------------")
#邏輯複雜的情況
def  handle_item(item):
    return (item*item)
list2=[handle_item(i) for i in range(21) if i%2==1]
print(list2)
#2.生成器表達式
print("...............................................")
odd_list1_gen=(i for  i in range(21) if i%2==1)
print(type(odd_list1_gen))
for item in odd_list1_gen:
    print(item)
print(".................list(odd_list1_gen)................")
listg=list(odd_list1_gen)
print(type(listg))
#3.字典推導式:
print("....................................................")
mydict={"sex":"female","name":"xiaopang","age":23}
#將字典的鍵和值互換產生一個新的列表
reversed_dict={value:key for key,value in mydict.items()}
print(reversed_dict)
print(id(mydict)==id(reversed_dict))
#集合推導式
print("。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。")
myset={key for key in mydict.items()}
print(myset)
print(type(myset))

#代碼運行結果:
H:\ANACONDA\python.exe I:/ainlp/pythonHight/chapter05/list_gentest.py
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]


[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
<class ‘list’>


[1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

<class ‘generator’>
1
3
5
7
9
11
13
15
17
19
…list(odd_list1_gen)…
<class ‘list’>

{‘female’: ‘sex’, ‘xiaopang’: ‘name’, 23: ‘age’}
False
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
{(‘name’, ‘xiaopang’), (‘sex’, ‘female’), (‘age’, 23)}
<class ‘set’>

Process finished with exit code 0

完結

下一篇 深入python的set和字典

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章