精华内容
下载资源
问答
  • Python创建自定义数据类型并访问,需要在定义类的时候对一些魔法方法逐一实现。 repr(obj)函数:此法给python解释器运行。 str(obj)函数:此法给人阅读。 说明: 1、str(obj)函数先查找obj.str()方法,若有此方法,...

    Python创建自定义数据类型并访问,需要在定义类的时候对一些魔法方法逐一实现。

    repr(obj)函数:此法给python解释器运行。

    str(obj)函数:此法给人阅读。

    说明:
    1、str(obj)函数先查找obj.str()方法,若有此方法,则调用并返回结果;
    2、若没有obj.str()方法,则再查找obj.repr()方法,若有此方法,则调用并返回结果;
    3、若obj.__repr__方法也不存在,则调用object类的__repr__实例方法,返回<main.XXXX object at 0xAABBCCDD>格式的字符串,此为内存地址

    # 打印显示类
    class Display(object):
        def show(self):
            return ", ".join("{}".format(getattr(self, key)) for key in self.__dict__)
        
        # 重写__str__定义对象的打印内容,否则只显示内存地址
        def __str__(self):
            return "{}".format(self.show())
    
    # 如:创建自定义字典类,需继承Display类,否则print时只会显示内存地址
    class DictDemo(Display):
        # 创建字典
        def __init__(self, key, value):
            self.dict = {}                  
            self.dict[key] = value
        
        # 通过__getitem__使用mytree[3]获取值的方式,否则不能使用mytree[3]方法获取值
        def __getitem__(self, key):
            return self.dict[key]
        
        # 通过__setitem__使用mytree[3]="red"方式,否则不能使用mytree[3]="red"方法
        def __setitem__(self, key, value):
            self.dict[key] = value
    
        # 通过__delitem__调用del方法,否则不能使用del方法
        def __delitem__(self, key):
        	del self.dict[key]
    
        # 通过__len__调用len()方法,否则不能使用len()方法
        def __len__(self):
            return len(self.dict)
    
        # 通过__contains__调用in方法,若一个集合类型没有实现__contains__方法,那么in运算符就会按顺序做一次迭代搜索。
        def __contains__(self, key):
            return key in self.dict
    
    dictDemo = DictDemo('key0','value0')    #方法一创建字典
    print(dictDemo['key0'])         		#结果为value0,dictDemo["key0"]会自动调用类中的__getitem__方法
    dictDemo['key1'] = 'value1'	    		#自动调用类中的__setitem__方法
    print(dictDemo['key1'])         		#结果为value1
    print(len(dictDemo))            		#结果为2,自动调用类中的__len__方法
    print(dictDemo)                 		#删除前
    del dictDemo['key0']            		#自动调用类中的__delitem__方法
    dictDemo['key2'] = 'value2'     		#自动调用类中的__setitem__方法
    print(dictDemo)                 		#删除后
    
    dictDemo1 = {"key0":"value0"}   		#方法二创建字典
    print(dictDemo1["key0"])        		#结果为value0
    
    # 通过__contains__调用in方法,若一个集合类型没有实现__contains__方法,那么in运算符就会按顺序做一次迭代搜索。
    if 'key0' in dictDemo1:
        print('in')
    

    结果为:

    value0
    value1
    2
    {'key0': 'value0', 'key1': 'value1'}
    {'key1': 'value1', 'key2': 'value2'}
    value0
    in
    
    展开全文
  • python numpy 自定义数据类型 import numpy as np dt = np.dtype([('name',np.str_,10),('age',np.int32,),('score',np.float,)])#自定义一个数据类型 ite1 = np.array([('DD',22,90),('JJ',20,89.0),('GG',21,95.8...

    python numpy 自定义数据类型

    import numpy as np
    
    dt = np.dtype([('name',np.str_,10),('age',np.int32,),('score',np.float32,)])#自定义一个数据类型
    ite1 = np.array([('DD',22,90),('JJ',20,89.0),('GG',21,95.8)],dtype=dt)
    print(ite1)

    输出结果:
    cmd输出结果

    展开全文
  • python 自定义文件类型

    2019-11-13 13:38:11
    一直在找python 自定义文件类型,用来保存敏感数据,现在终于找到一个比较满意的了。 直接上代码 import pickle li = ["nihao","haloo",{"sdf":123}] with open("test.xxx","wb") as fb: pickle.dump(li,fb) ...

    一直在找python 自定义文件类型,用来保存敏感数据,现在终于找到一个比较满意的了。
    直接上代码

    import  pickle
    
    li = ["nihao","haloo",{"sdf":123}]
    
    with open("test.xxx","wb") as fb:
        pickle.dump(li,fb)
    
    with open("test.xxx","rb") as fb:
        ss=pickle.load(fb)
        print(type(ss),ss,type(ss[2]["sdf"]))
    

    生成 文件test.xxx
    查询结果是

    <class 'list'> ['nihao', 'haloo', {'sdf': 123}] <class 'int'>
    
    展开全文
  • python自定义序列类型

    2019-09-02 18:24:11
    序列类型的分类 可以按照两个维度对序列进行分类 1.根据数据的维度进行区分             1.容器序列:list 、tuple 、 deque     ...

    序列类型的分类

    可以按照两个维度对序列进行分类
    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和字典

    展开全文
  • python自定义类型转json

    千次阅读 2016-04-27 11:37:25
    json模块不仅可以处理普通的python内置类型,也可以处理我们自定义数据类型,而往往处理自定义的对象是很常用的。 首先,我们定义一个类Person。 class Person(object): def __init__(self,name,age): self.name...
  • 这里用一个简单的实例来说明: class Character: def __init__(self,... Health: 20 ——来自 coursera The Rice的课程 An Introduction to Interactive Programming in Python (Part 2) —Object-oriented Programming
  • 您可能感兴趣的文章:Python isinstance判断对象类型深入浅析Python获取对象信息的函数type()、isinstance()、dir()Python中请使用isinstance()判断变量类型python数据类型判断type与isinstance的区别实例解析Python
  • Python类创建一个自定义数据类型

    万次阅读 2019-01-01 15:36:29
    创建一个新的拥有一些额外功能的实例属性类型,比如类型检查。 # Descriptor attribute for an integer type-checked attribute class String(object): def __init__(self, name): self.name = name def __get__...
  • 数据类型定义: &gt;&gt;&gt; dt = np.dtype('&gt;i4') 定义一个big-endian int 4*8=32位的数据类型 &gt;&gt;&gt; dt dtype('&gt;i4') &gt;&gt;&gt; dt.byteorder /...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,471
精华内容 588
关键字:

python自定义数据类型

python 订阅