• 基本数据类型


    数字(number)

    布尔型(bool)

    bool型只有两个值:Ture和False

    之所以将bool值归类为数字,是因为我们习惯用1表示Ture,0表示False。

    整型(int)

    Python中的整型属于int类型,,默认用十进制表示,此外,也支持二进制,八进制,十六进制表示方法。

    进制转换

    尽管计算机只认识二进制,但是为了迎合我们的习惯python中的数字还是默认十进制。里面还内置了一些方法来帮助我们转换,比如把十进制转换为二进制使用方法,

    在转换结果前加'0b'表示是一个二进制数。

    既然十进制可以转换为二进制,那么其实使用同样的原理也可以转换为其他进制,python也为我们提供了十进制转换为八进制和十六进制的方法,分别是oct和hex,

    八进制前面要以'0o'标示,十六进制要以'0x'标示。

    a=bin(10)#把10转换为二进制
    print(a)
    #输出:0b1010
    
    b=oct(10)#把10转换为八进制
    print(b)
    #输出:0o12
    
    c=hex(10)#把10转换为十六进制
    print(c)
    #输出:0xa

    基本运算

    print(2+3)
    #输出:5
    
    print(2-3)
    #输出:-1
    
    print(2*3)
    #输出:6
    
    print(3/2)#除法
    #输出:1.5
    
    print(5%2)#取余数
    #输出:1
    
    print(3//2)#返回商的整数部分
    #输出:1
    
    print(2**3)#2的3次方
    #输出:8
    
    print(divmod(16,3))#以元祖的形式返回16/3的商和余数
    #输出:(5, 1)
    class int(object):
        """
        int(x=0) -> int or long
        int(x, base=10) -> int or long
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is floating point, the conversion truncates towards zero.
        If x is outside the integer range, the function returns a long instead.
        
        If x is not a number or if base is given, then x must be a string or
        Unicode object representing an integer literal in the given base.  The
        literal can be preceded by '+' or '-' and be surrounded by whitespace.
        The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
        interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        """
        def bit_length(self): 
            """ 返回表示该数字的时占用的最少位数 """
            """
            int.bit_length() -> int
            
            Number of bits necessary to represent self in binary.
            >>> bin(37)
            '0b100101'
            >>> (37).bit_length()
            """
            return 0
    
        def conjugate(self, *args, **kwargs): # real signature unknown
            """ 返回该复数的共轭复数 """
            """ Returns self, the complex conjugate of any int. """
            pass
    
        def __abs__(self):
            """ 返回绝对值 """
            """ x.__abs__() <==> abs(x) """
            pass
    
        def __add__(self, y):
            """ x.__add__(y) <==> x+y """
            pass
    
        def __and__(self, y):
            """ x.__and__(y) <==> x&y """
            pass
    
        def __cmp__(self, y): 
            """ 比较两个数大小 """
            """ x.__cmp__(y) <==> cmp(x,y) """
            pass
    
        def __coerce__(self, y):
            """ 强制生成一个元组 """ 
            """ x.__coerce__(y) <==> coerce(x, y) """
            pass
    
        def __divmod__(self, y): 
            """ 相除,得到商和余数组成的元组 """ 
            """ x.__divmod__(y) <==> divmod(x, y) """
            pass
    
        def __div__(self, y): 
            """ x.__div__(y) <==> x/y """
            pass
    
        def __float__(self): 
            """ 转换为浮点类型 """ 
            """ x.__float__() <==> float(x) """
            pass
    
        def __floordiv__(self, y): 
            """ x.__floordiv__(y) <==> x//y """
            pass
    
        def __format__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __getattribute__(self, name): 
            """ x.__getattribute__('name') <==> x.name """
            pass
    
        def __getnewargs__(self, *args, **kwargs): # real signature unknown
            """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
            pass
    
        def __hash__(self): 
            """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
            """ x.__hash__() <==> hash(x) """
            pass
    
        def __hex__(self): 
            """ 返回当前数的 十六进制 表示 """ 
            """ x.__hex__() <==> hex(x) """
            pass
    
        def __index__(self): 
            """ 用于切片,数字无意义 """
            """ x[y:z] <==> x[y.__index__():z.__index__()] """
            pass
    
        def __init__(self, x, base=10): # known special case of int.__init__
            """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
            """
            int(x=0) -> int or long
            int(x, base=10) -> int or long
            
            Convert a number or string to an integer, or return 0 if no arguments
            are given.  If x is floating point, the conversion truncates towards zero.
            If x is outside the integer range, the function returns a long instead.
            
            If x is not a number or if base is given, then x must be a string or
            Unicode object representing an integer literal in the given base.  The
            literal can be preceded by '+' or '-' and be surrounded by whitespace.
            The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
            interpret the base from the string as an integer literal.
            >>> int('0b100', base=0)
            # (copied from class doc)
            """
            pass
    
        def __int__(self): 
            """ 转换为整数 """ 
            """ x.__int__() <==> int(x) """
            pass
    
        def __invert__(self): 
            """ x.__invert__() <==> ~x """
            pass
    
        def __long__(self): 
            """ 转换为长整数 """ 
            """ x.__long__() <==> long(x) """
            pass
    
        def __lshift__(self, y): 
            """ x.__lshift__(y) <==> x<<y """
            pass
    
        def __mod__(self, y): 
            """ x.__mod__(y) <==> x%y """
            pass
    
        def __mul__(self, y): 
            """ x.__mul__(y) <==> x*y """
            pass
    
        def __neg__(self): 
            """ x.__neg__() <==> -x """
            pass
    
        @staticmethod # known case of __new__
        def __new__(S, *more): 
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass
    
        def __nonzero__(self): 
            """ x.__nonzero__() <==> x != 0 """
            pass
    
        def __oct__(self): 
            """ 返回改值的 八进制 表示 """ 
            """ x.__oct__() <==> oct(x) """
            pass
    
        def __or__(self, y): 
            """ x.__or__(y) <==> x|y """
            pass
    
        def __pos__(self): 
            """ x.__pos__() <==> +x """
            pass
    
        def __pow__(self, y, z=None): 
            """ 幂,次方 """ 
            """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
            pass
    
        def __radd__(self, y): 
            """ x.__radd__(y) <==> y+x """
            pass
    
        def __rand__(self, y): 
            """ x.__rand__(y) <==> y&x """
            pass
    
        def __rdivmod__(self, y): 
            """ x.__rdivmod__(y) <==> divmod(y, x) """
            pass
    
        def __rdiv__(self, y): 
            """ x.__rdiv__(y) <==> y/x """
            pass
    
        def __repr__(self): 
            """转化为解释器可读取的形式 """
            """ x.__repr__() <==> repr(x) """
            pass
    
        def __str__(self): 
            """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
            """ x.__str__() <==> str(x) """
            pass
    
        def __rfloordiv__(self, y): 
            """ x.__rfloordiv__(y) <==> y//x """
            pass
    
        def __rlshift__(self, y): 
            """ x.__rlshift__(y) <==> y<<x """
            pass
    
        def __rmod__(self, y): 
            """ x.__rmod__(y) <==> y%x """
            pass
    
        def __rmul__(self, y): 
            """ x.__rmul__(y) <==> y*x """
            pass
    
        def __ror__(self, y): 
            """ x.__ror__(y) <==> y|x """
            pass
    
        def __rpow__(self, x, z=None): 
            """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
            pass
    
        def __rrshift__(self, y): 
            """ x.__rrshift__(y) <==> y>>x """
            pass
    
        def __rshift__(self, y): 
            """ x.__rshift__(y) <==> x>>y """
            pass
    
        def __rsub__(self, y): 
            """ x.__rsub__(y) <==> y-x """
            pass
    
        def __rtruediv__(self, y): 
            """ x.__rtruediv__(y) <==> y/x """
            pass
    
        def __rxor__(self, y): 
            """ x.__rxor__(y) <==> y^x """
            pass
    
        def __sub__(self, y): 
            """ x.__sub__(y) <==> x-y """
            pass
    
        def __truediv__(self, y): 
            """ x.__truediv__(y) <==> x/y """
            pass
    
        def __trunc__(self, *args, **kwargs): 
            """ 返回数值被截取为整形的值,在整形中无意义 """
            pass
    
        def __xor__(self, y): 
            """ x.__xor__(y) <==> x^y """
            pass
    
        denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 分母 = 1 """
        """the denominator of a rational number in lowest terms"""
    
        imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 虚数,无意义 """
        """the imaginary part of a complex number"""
    
        numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 分子 = 数字大小 """
        """the numerator of a rational number in lowest terms"""
    
        real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """ 实属,无意义 """
        """the real part of a complex number"""
    
    int
    整型(int)

    浮点数(float)

     浮点数是属于有理数当中的,Python中的浮点数就是数学当中的小数,在运算中,整数与浮点数运算的结果依旧是浮点数,可以理解为向高精度方向转换。

    为什么叫做float浮点型呢?

    浮点数也就是小数,之所以称为浮点数,是因为按照科学计数法表示时,浮点数的小数点是可以移动的,比如:

    1.23*10^9和12.3*10^8是相等的。

    浮点数可以用数学写法,如1.23,3.14,-9.07,等等。但是对于很大或者很小的浮点数,就必须用科学计数法表示,用e来代替10,比如:

    1.23*10^9就是1.23e9,或者12.3e8,再比如0.000012可以写成1.2e-5,等等

    整数和浮点数在计算机内部储存方式是不同的,整数永远是精准的,而浮点数运算可能会进行四舍五入而产生误差

    关于小数不精准的问题

    Python默认的是17位 精度,也就是小数点后16位,尽管有16位,但是这个精度越往后是越不准的

    首先,这个问题并不是Python独有,其他语言也有同样的问题

    其次,小数不精准是因为在转换成二进制的过程中会产生无限循环的情况,在约省的时候就会出现误差

    比如11.2的小数部分0.2转换为二进制是无限循环00110011001100110011....(十进制小数部分转二进制可自行百度,其实就是一个乘以2再取整的过程)

    单精度在存储的时候用23bit来存放这个尾数部分,(前面9bit存储指数和符号)

    那么,需要更高精度却超过16位小数该怎么办?

    这里就需要借助decimal模块的'getcontxet'‘decimal’方法

    a=1.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
    print(a)
    #输出:1.0123456789101113   整数位1位,小数点后16位,默认精度17位
    from decimal import *
    print(getcontext())
    #输出:Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
    #  capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
    getcontext().prec = 50#精确到小数点后50位
    a=Decimal(1)/Decimal(3)#将1和3转换为decimal类型,这里必须是传入整型或者字符型参数才能准确
    print(a)
    #输出:0.33333333333333333333333333333333333333333333333333  小数点后共50个3

    但是如果现在已经这样定义

    a=1.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950

    那么无论如何,你都得不到这个值,不管你用什么模块什么方法!因为在计算机内部储存的绝对不是这个值,绝对有误差!

    这样行不行?显然不行,已定义情况下只能保证17位的精度

    #想精确的输出a,下面这种方法行不行?
    a=1.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
    from decimal import *
    print(getcontext())
    #输出:Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
    #  capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
    b=Decimal.from_float(a)#把a转变成decimal型
    print(b)
    #输出:1.0123456789101112907047763656009919941425323486328125  显然出错,因为float本身就是不准确的

    怎么办,这样呢?

    #?怎么办,这样行不行?
    from decimal import *
    a=1.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
    b=str(a)
    print(type(b))
    #输出:<class 'str'>
    print(b)
    #输出:1.0123456789101113
    Decimal(b)
    print(type(b))
    #输出:<class 'str'>
    print(b)
    #输出:1.0123456789101113

    好吧,也不行滴!

    只能这样干:(虽然失去了数学上的意义了,失去讨论价值)

    a=('1.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950')
    print(a)
    #输出:1.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
    更多关于数字请点击这里 

    字符串(str)

    创建:

    s='Hello World'

    注意:

    1、字符串的单引号或者双引号都无法取消特殊字符的含义,如果想让引号内所有的字符均取消特殊含义,在引号前面加r,如name=r'i hf'

    2、Unicode字符串与u连用,并且必须在r前面,如:name=ur'i hf'

    索引

    s='Hello World'
    print(s[1])
    #输出:e
    print(s[-1])
    #输出:d
    print(s.index('W'))
    #输出:6                 注意索引都是从0开始,前面有个空格
    索引

    查找

    s='Hello World'
    print(s.find('W'))
    #输出:6
    print(s.find('n'))
    #输出:-1    如果里面没有,输出-1
    查找

    移除

    s='   Hello World    '
    print(s.strip())#字符串的strip()方法可以去掉字符串中左边和右边指定字符,默认是空格
    #输出:Hello World
    
    s='**Hello World**'
    print(s.lstrip('*'))#字符串的lstrip()方法可以去掉字符串中左边的指定字符,默认是空格
    #输出:Hello World**
    
    s='**Hello World**'
    print(s.rstrip('*'))#字符串的lstrip()方法可以去掉字符串中右边的指定字符,默认是空格
    #输出:**Hello World
    移除

    长度

    ss='12345678'
    print(len(ss))#len()可以统计字符串当中的字符数量
    #输出:8
    长度

    切片

    s='hello world'
    
    print(s[0:4])#取0~3,4不取
    #输出:hell
    
    print(s[:-1])#从头取到尾
    #输出:hello world
    
    print(s[:8:2])#从0取到7,步长为2
    #输出:hlow
    
    print(s[::2])#从头取到尾,步长为2
    #输出:hlowrd
    
    print(s[::-1])#倒着取
    #输出:dlrow olleh
    切片

    循环

    name1=['彭于晏','胡歌','在下','胡歌','胡歌','胡歌']
    for j in  name1:
        print(j)
    #输出:彭于晏
    #        胡歌
    #        在下
    #        胡歌
    #        胡歌
    #        胡歌
    View Code

    其他

    name.capitalize()  首字母大写
    name.casefold()   大写全部变小写
    name.center(50,"-")  输出 '---------------------Alex Li----------------------'
    name.count('lex') 统计 lex出现次数
    name.encode()  将字符串编码成bytes格式
    name.endswith("Li")  判断字符串是否以 Li结尾
     "Alex	Li".expandtabs(10) 输出'Alex      Li', 将	转换成多长的空格 
     name.find('A')  查找A,找到返回其索引, 找不到返回-1 
    
    format :
        >>> msg = "my name is {}, and age is {}"
        >>> msg.format("alex",22)
        'my name is alex, and age is 22'
        >>> msg = "my name is {1}, and age is {0}"
        >>> msg.format("alex",22)
        'my name is 22, and age is alex'
        >>> msg = "my name is {name}, and age is {age}"
        >>> msg.format(age=22,name="ale")
        'my name is ale, and age is 22'
    format_map
        >>> msg.format_map({'name':'alex','age':22})
        'my name is alex, and age is 22'
    
    
    msg.index('a')  返回a所在字符串的索引
    '9aA'.isalnum()   True
    
    '9'.isdigit() 是否整数
    name.isnumeric  
    name.isprintable
    name.isspace
    name.istitle
    name.isupper
     "|".join(['alex','jack','rain'])
    'alex|jack|rain'
    
    
    maketrans
        >>> intab = "aeiou"  #This is the string having actual characters. 
        >>> outtab = "12345" #This is the string having corresponding mapping character
        >>> trantab = str.maketrans(intab, outtab)
        >>> 
        >>> str = "this is string example....wow!!!"
        >>> str.translate(trantab)
        'th3s 3s str3ng 2x1mpl2....w4w!!!'
    
     msg.partition('is')   输出 ('my name ', 'is', ' {name}, and age is {age}') 
    
     >>> "alex li, chinese name is lijie".replace("li","LI",1)
         'alex LI, chinese name is lijie'
    
     msg.swapcase 大小写互换
    
    
     >>> msg.zfill(40)
    '00000my name is {name}, and age is {age}'
    
    
    
    >>> n4.ljust(40,"-")
    'Hello 2orld-----------------------------'
    >>> n4.rjust(40,"-")
    '-----------------------------Hello 2orld'
    
    
    >>> b="ddefdsdff_哈哈" 
    >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
    True
    其他

    字符串工厂函数

    class str(basestring):
        """
        str(object='') -> string
        
        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        """
        def capitalize(self):  
            """ 首字母变大写 """
            """
            S.capitalize() -> string
            
            Return a copy of the string S with only its first character
            capitalized.
            """
            return ""
    
        def center(self, width, fillchar=None):  
            """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
            """
            S.center(width[, fillchar]) -> string
            
            Return S centered in a string of length width. Padding is
            done using the specified fill character (default is a space)
            """
            return ""
    
        def count(self, sub, start=None, end=None):  
            """ 子序列个数 """
            """
            S.count(sub[, start[, end]]) -> int
            
            Return the number of non-overlapping occurrences of substring sub in
            string S[start:end].  Optional arguments start and end are interpreted
            as in slice notation.
            """
            return 0
    
        def decode(self, encoding=None, errors=None):  
            """ 解码 """
            """
            S.decode([encoding[,errors]]) -> object
            
            Decodes S using the codec registered for encoding. encoding defaults
            to the default encoding. errors may be given to set a different error
            handling scheme. Default is 'strict' meaning that encoding errors raise
            a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
            as well as any other name registered with codecs.register_error that is
            able to handle UnicodeDecodeErrors.
            """
            return object()
    
        def encode(self, encoding=None, errors=None):  
            """ 编码,针对unicode """
            """
            S.encode([encoding[,errors]]) -> object
            
            Encodes S using the codec registered for encoding. encoding defaults
            to the default encoding. errors may be given to set a different error
            handling scheme. Default is 'strict' meaning that encoding errors raise
            a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
            'xmlcharrefreplace' as well as any other name registered with
            codecs.register_error that is able to handle UnicodeEncodeErrors.
            """
            return object()
    
        def endswith(self, suffix, start=None, end=None):  
            """ 是否以 xxx 结束 """
            """
            S.endswith(suffix[, start[, end]]) -> bool
            
            Return True if S ends with the specified suffix, False otherwise.
            With optional start, test S beginning at that position.
            With optional end, stop comparing S at that position.
            suffix can also be a tuple of strings to try.
            """
            return False
    
        def expandtabs(self, tabsize=None):  
            """ 将tab转换成空格,默认一个tab转换成8个空格 """
            """
            S.expandtabs([tabsize]) -> string
            
            Return a copy of S where all tab characters are expanded using spaces.
            If tabsize is not given, a tab size of 8 characters is assumed.
            """
            return ""
    
        def find(self, sub, start=None, end=None):  
            """ 寻找子序列位置,如果没找到,返回 -1 """
            """
            S.find(sub [,start [,end]]) -> int
            
            Return the lowest index in S where substring sub is found,
            such that sub is contained within S[start:end].  Optional
            arguments start and end are interpreted as in slice notation.
            
            Return -1 on failure.
            """
            return 0
    
        def format(*args, **kwargs): # known special case of str.format
            """ 字符串格式化,动态参数,将函数式编程时细说 """
            """
            S.format(*args, **kwargs) -> string
            
            Return a formatted version of S, using substitutions from args and kwargs.
            The substitutions are identified by braces ('{' and '}').
            """
            pass
    
        def index(self, sub, start=None, end=None):  
            """ 子序列位置,如果没找到,报错 """
            S.index(sub [,start [,end]]) -> int
            
            Like S.find() but raise ValueError when the substring is not found.
            """
            return 0
    
        def isalnum(self):  
            """ 是否是字母和数字 """
            """
            S.isalnum() -> bool
            
            Return True if all characters in S are alphanumeric
            and there is at least one character in S, False otherwise.
            """
            return False
    
        def isalpha(self):  
            """ 是否是字母 """
            """
            S.isalpha() -> bool
            
            Return True if all characters in S are alphabetic
            and there is at least one character in S, False otherwise.
            """
            return False
    
        def isdigit(self):  
            """ 是否是数字 """
            """
            S.isdigit() -> bool
            
            Return True if all characters in S are digits
            and there is at least one character in S, False otherwise.
            """
            return False
    
        def islower(self):  
            """ 是否小写 """
            """
            S.islower() -> bool
            
            Return True if all cased characters in S are lowercase and there is
            at least one cased character in S, False otherwise.
            """
            return False
    
        def isspace(self):  
            """
            S.isspace() -> bool
            
            Return True if all characters in S are whitespace
            and there is at least one character in S, False otherwise.
            """
            return False
    
        def istitle(self):  
            """
            S.istitle() -> bool
            
            Return True if S is a titlecased string and there is at least one
            character in S, i.e. uppercase characters may only follow uncased
            characters and lowercase characters only cased ones. Return False
            otherwise.
            """
            return False
    
        def isupper(self):  
            """
            S.isupper() -> bool
            
            Return True if all cased characters in S are uppercase and there is
            at least one cased character in S, False otherwise.
            """
            return False
    
        def join(self, iterable):  
            """ 连接 """
            """
            S.join(iterable) -> string
            
            Return a string which is the concatenation of the strings in the
            iterable.  The separator between elements is S.
            """
            return ""
    
        def ljust(self, width, fillchar=None):  
            """ 内容左对齐,右侧填充 """
            """
            S.ljust(width[, fillchar]) -> string
            
            Return S left-justified in a string of length width. Padding is
            done using the specified fill character (default is a space).
            """
            return ""
    
        def lower(self):  
            """ 变小写 """
            """
            S.lower() -> string
            
            Return a copy of the string S converted to lowercase.
            """
            return ""
    
        def lstrip(self, chars=None):  
            """ 移除左侧空白 """
            """
            S.lstrip([chars]) -> string or unicode
            
            Return a copy of the string S with leading whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            If chars is unicode, S will be converted to unicode before stripping
            """
            return ""
    
        def partition(self, sep):  
            """ 分割,前,中,后三部分 """
            """
            S.partition(sep) -> (head, sep, tail)
            
            Search for the separator sep in S, and return the part before it,
            the separator itself, and the part after it.  If the separator is not
            found, return S and two empty strings.
            """
            pass
    
        def replace(self, old, new, count=None):  
            """ 替换 """
            """
            S.replace(old, new[, count]) -> string
            
            Return a copy of string S with all occurrences of substring
            old replaced by new.  If the optional argument count is
            given, only the first count occurrences are replaced.
            """
            return ""
    
        def rfind(self, sub, start=None, end=None):  
            """
            S.rfind(sub [,start [,end]]) -> int
            
            Return the highest index in S where substring sub is found,
            such that sub is contained within S[start:end].  Optional
            arguments start and end are interpreted as in slice notation.
            
            Return -1 on failure.
            """
            return 0
    
        def rindex(self, sub, start=None, end=None):  
            """
            S.rindex(sub [,start [,end]]) -> int
            
            Like S.rfind() but raise ValueError when the substring is not found.
            """
            return 0
    
        def rjust(self, width, fillchar=None):  
            """
            S.rjust(width[, fillchar]) -> string
            
            Return S right-justified in a string of length width. Padding is
            done using the specified fill character (default is a space)
            """
            return ""
    
        def rpartition(self, sep):  
            """
            S.rpartition(sep) -> (head, sep, tail)
            
            Search for the separator sep in S, starting at the end of S, and return
            the part before it, the separator itself, and the part after it.  If the
            separator is not found, return two empty strings and S.
            """
            pass
    
        def rsplit(self, sep=None, maxsplit=None):  
            """
            S.rsplit([sep [,maxsplit]]) -> list of strings
            
            Return a list of the words in the string S, using sep as the
            delimiter string, starting at the end of the string and working
            to the front.  If maxsplit is given, at most maxsplit splits are
            done. If sep is not specified or is None, any whitespace string
            is a separator.
            """
            return []
    
        def rstrip(self, chars=None):  
            """
            S.rstrip([chars]) -> string or unicode
            
            Return a copy of the string S with trailing whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            If chars is unicode, S will be converted to unicode before stripping
            """
            return ""
    
        def split(self, sep=None, maxsplit=None):  
            """ 分割, maxsplit最多分割几次 """
            """
            S.split([sep [,maxsplit]]) -> list of strings
            
            Return a list of the words in the string S, using sep as the
            delimiter string.  If maxsplit is given, at most maxsplit
            splits are done. If sep is not specified or is None, any
            whitespace string is a separator and empty strings are removed
            from the result.
            """
            return []
    
        def splitlines(self, keepends=False):  
            """ 根据换行分割 """
            """
            S.splitlines(keepends=False) -> list of strings
            
            Return a list of the lines in S, breaking at line boundaries.
            Line breaks are not included in the resulting list unless keepends
            is given and true.
            """
            return []
    
        def startswith(self, prefix, start=None, end=None):  
            """ 是否起始 """
            """
            S.startswith(prefix[, start[, end]]) -> bool
            
            Return True if S starts with the specified prefix, False otherwise.
            With optional start, test S beginning at that position.
            With optional end, stop comparing S at that position.
            prefix can also be a tuple of strings to try.
            """
            return False
    
        def strip(self, chars=None):  
            """ 移除两段空白 """
            """
            S.strip([chars]) -> string or unicode
            
            Return a copy of the string S with leading and trailing
            whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            If chars is unicode, S will be converted to unicode before stripping
            """
            return ""
    
        def swapcase(self):  
            """ 大写变小写,小写变大写 """
            """
            S.swapcase() -> string
            
            Return a copy of the string S with uppercase characters
            converted to lowercase and vice versa.
            """
            return ""
    
        def title(self):  
            """
            S.title() -> string
            
            Return a titlecased version of S, i.e. words start with uppercase
            characters, all remaining cased characters have lowercase.
            """
            return ""
    
        def translate(self, table, deletechars=None):  
            """
            转换,需要先做一个对应表,最后一个表示删除字符集合
            intab = "aeiou"
            outtab = "12345"
            trantab = maketrans(intab, outtab)
            str = "this is string example....wow!!!"
            print str.translate(trantab, 'xm')
            """
    
            """
            S.translate(table [,deletechars]) -> string
            
            Return a copy of the string S, where all characters occurring
            in the optional argument deletechars are removed, and the
            remaining characters have been mapped through the given
            translation table, which must be a string of length 256 or None.
            If the table argument is None, no translation is applied and
            the operation simply removes the characters in deletechars.
            """
            return ""
    
        def upper(self):  
            """
            S.upper() -> string
            
            Return a copy of the string S converted to uppercase.
            """
            return ""
    
        def zfill(self, width):  
            """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
            """
            S.zfill(width) -> string
            
            Pad a numeric string S with zeros on the left, to fill a field
            of the specified width.  The string S is never truncated.
            """
            return ""
    
        def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
            pass
    
        def _formatter_parser(self, *args, **kwargs): # real signature unknown
            pass
    
        def __add__(self, y):  
            """ x.__add__(y) <==> x+y """
            pass
    
        def __contains__(self, y):  
            """ x.__contains__(y) <==> y in x """
            pass
    
        def __eq__(self, y):  
            """ x.__eq__(y) <==> x==y """
            pass
    
        def __format__(self, format_spec):  
            """
            S.__format__(format_spec) -> string
            
            Return a formatted version of S as described by format_spec.
            """
            return ""
    
        def __getattribute__(self, name):  
            """ x.__getattribute__('name') <==> x.name """
            pass
    
        def __getitem__(self, y):  
            """ x.__getitem__(y) <==> x[y] """
            pass
    
        def __getnewargs__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __getslice__(self, i, j):  
            """
            x.__getslice__(i, j) <==> x[i:j]
                       
                       Use of negative indices is not supported.
            """
            pass
    
        def __ge__(self, y):  
            """ x.__ge__(y) <==> x>=y """
            pass
    
        def __gt__(self, y):  
            """ x.__gt__(y) <==> x>y """
            pass
    
        def __hash__(self):  
            """ x.__hash__() <==> hash(x) """
            pass
    
        def __init__(self, string=''): # known special case of str.__init__
            """
            str(object='') -> string
            
            Return a nice string representation of the object.
            If the argument is a string, the return value is the same object.
            # (copied from class doc)
            """
            pass
    
        def __len__(self):  
            """ x.__len__() <==> len(x) """
            pass
    
        def __le__(self, y):  
            """ x.__le__(y) <==> x<=y """
            pass
    
        def __lt__(self, y):  
            """ x.__lt__(y) <==> x<y """
            pass
    
        def __mod__(self, y):  
            """ x.__mod__(y) <==> x%y """
            pass
    
        def __mul__(self, n):  
            """ x.__mul__(n) <==> x*n """
            pass
    
        @staticmethod # known case of __new__
        def __new__(S, *more):  
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass
    
        def __ne__(self, y):  
            """ x.__ne__(y) <==> x!=y """
            pass
    
        def __repr__(self):  
            """ x.__repr__() <==> repr(x) """
            pass
    
        def __rmod__(self, y):  
            """ x.__rmod__(y) <==> y%x """
            pass
    
        def __rmul__(self, n):  
            """ x.__rmul__(n) <==> n*x """
            pass
    
        def __sizeof__(self):  
            """ S.__sizeof__() -> size of S in memory, in bytes """
            pass
    
        def __str__(self):  
            """ x.__str__() <==> str(x) """
            pass
    
    str
    字符串工厂函数
    更多关于字符串请点击这里 

    列表(list)

    列表是最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

    定义列表:

    1 love=['i love you','我爱你''あなたのことが好きです']#list列表定义用中括号,中间用逗号隔开,当然要在英文输入下

    通过下标访问列表中的元素,下标从0开始计数

    1 love=['i love you','我爱你','あなたのことが好きです']
    2 print(love[0])
    3 print(love[1])
    4 print(love[2])
    5 print(love[-1])#还可以倒着取
    6 print(love[-2])

    输出:

    C:Pythonpython.exe C:/Python/leetcode/1.py
    i love you
    我爱你
    あなたのことが好きです
    あなたのことが好きです
    我爱你
    
    Process finished with exit code 0
    

    切片:取多个元素

     1 love=['i love you','我爱你','あなたのことが好きです','사랑해','吾爱汝','我愛你']
     2 
     3 print(love[1:4])#取下标1至下标4之间的数字,包括1,不包括4
     4 # 输出:['我爱你', 'あなたのことが好きです', '사랑해']切片之后得到的还是一个列表
     5 
     6 print(love[1:-1])#取下标1至-1的值,不包括-1
     7 # 输出:['我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝']
     8 
     9 print(love[:3])#从头开始取,一直取到下标2,3不取
    10 # 输出:['i love you', '我爱你', 'あなたのことが好きです']
    11 
    12 print(love[3:])#从下标3开始取,一直到最后一个,必须不能写-1,只能这么写
    13 # 输出:['사랑해', '吾爱汝', '我愛你']
    14 
    15 print(love[3:-1])#这样-1就不会被包含了
    16 # 输出:['사랑해', '吾爱汝']
    17 
    18 print(love[0::2])#后面的2是代表步长是2,就是每隔一个元素,就取一个
    19 # 输出:['i love you', 'あなたのことが好きです', '吾爱汝']
    20 
    21 print(love[::2])#和上句效果一样
    22 # 输出:['i love you', 'あなたのことが好きです', '吾爱汝']
    View Code

    追加

    love=['i love you','我爱你','あなたのことが好きです','사랑해','吾爱汝','我愛你']
    
    love.append('我是新来的')#.append是在列表的最后面添加新的元素
    love.append([123])#再次在后面添加一个列表
    print(love)
    #输出:['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你', '我是新来的', [123]]
    View Code

    插入

    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你',]
    
    love.insert(1,"放到下标是1的位置")#注意这里要用双引号来包括单引号
    print(love)
    #输出:['i love you', '放到下标是1的位置', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你']
    
    love.insert(5,9999)#把数字 9999 放到下标为5的位置
    print(love)
    #输出:['i love you', '放到下标是1的位置', '我爱你', 'あなたのことが好きです', '사랑해', 9999, '吾爱汝', '我愛你']
    View Code

    修改

    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你',]
    
    love[1]='我不爱你了'
    print(love)
    #输出:['i love you', '我不爱你了', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你']
    View Code

    删除

    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你',]
    
    del love[1]#指定下标删除元素
    print(love)
    #输出:['i love you', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你']
    
    love.remove('i love you')#.remove可以删除指定元素
    print(love)
    #输出:['あなたのことが好きです', '사랑해', '吾爱汝', '我愛你']
    
    love.pop()#删除列表最后一个元素
    print(love)
    #输出:['あなたのことが好きです', '사랑해', '吾爱汝']
    View Code

    循环

    循环
    name1=['彭于晏','胡歌','在下','胡歌','胡歌','胡歌']
    for j in  name1:
        print(j)
    #输出:彭于晏
    #        胡歌
    #        在下
    #        胡歌
    #        胡歌
    #        胡歌

    长度

    name=['胡歌','彭于晏','在下','好看']
    print(len(name))#计算列表的长度
    #输出:4
    长度

    包含

    name=['胡歌','彭于晏','在下','好看']
    a='胡歌'in name
    b='haha'in name
    print(a)
    #输出:True
    print(b)
    #输出:False
    包含

    扩展

    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你',]
    
    love2=[1,2,3]
    love.extend(love2)#.extend把列表love2中的元素添加到列表love中
    print(love)
    #输出:['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你', 1, 2, 3]
    View Code

    拷贝

    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你',]
    
    love2=love.copy()#把列表love复制给列表love2
    print(love2)
    #输出:['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你']
    View Code

    统计

    love=['i love you', '我爱你', 'あなたのことが好きです','i love you', '사랑해', '吾爱汝', '我愛你','i love you']
    
    a=love.count('i love you')#统计列表love当中  'i love you'   的个数
    print(a)
    #输出:3
    View Code

    排序

    反转排序.reverse()

    列表反转排序。把原列表中的元素顺序从左至右反转过来重新存放,而不会对列表中的参数进行排序整理,即不会根据大小排序。

    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你',23,1,89]
    
    love.reverse()#列表反转排序。把原列表中的元素顺序从左至右反转过来重新存放,而不会对列表中的参数进行排序整理,即不会根据大小排序。
    print(love)
    #输出:[89, 1, 23, '我愛你', '吾爱汝', '사랑해', 'あなたのことが好きです', '我爱你', 'i love you']
    View Code

    升序排序.sort()

    对列表内容进行升序排序,直接修改原列表的排序,排序后的新列表会覆盖原列表。注意:这种情况下列表里的元素必须是同一种数据类型

    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你',23,1,89]
    
    love.sort()
    print(love)
    #输出:Traceback (most recent call last):
    #  File "C:/Python/leetcode/1.py", line 5, in <module>
    #   love.sort()
    #TypeError: unorderable types: int() < str()                列表里既有数字又有字符串,Python就没办法比较
    
    ###############################################
    
    love=['i love you', '我爱你', 'あなたのことが好きです', '사랑해', '吾爱汝', '我愛你']
    
    love.sort()#列表里全是字符串类型的元素,就可以进行升序排列,同时新的顺序会覆盖原有顺序
    print(love)
    #输出:['i love you', 'あなたのことが好きです', '吾爱汝', '我愛你', '我爱你', '사랑해']
    
    ###############################################
    
    love=[2, 4 ,3,16, 0, 9]
    
    love.sort()#列表里全是数字类型的元素,就可以进行升序排列,同时新的顺序会覆盖原有顺序
    print(love)
    #输出:[0, 2, 3, 4, 9, 16]
    View Code

    获取下标

    love=['i love you', '我爱你', 'あなたのことが好きです','我爱你', '사랑해', '吾爱汝', '我愛你']
    
    a=love.index('我爱你')#只返回找到的第一个下标
    print(a)
    #输出:1
    View Code
    更多关于列表请点击这里

    列表与字符串的分割(split)和连接(join)

    分割(split)  

    描述

      Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串

    split() 方法语法

    str.split(str="", num=string.count(str)).

    参数

    • str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等
    • num -- 分割次数

    返回值

          返回分割后的字符串列表

    实例

    以下实例展示了split()函数的使用方法:

    str="彭于晏
    胡歌
    和在下
    都很帅"
    print(str.split( ))#分隔符,默认为所有的空字符,包括空格、换行(
    )、制表符(	)等
    #输出:['彭于晏', '胡歌', '和在下', '都很帅']
    print(str.split('
    ',1 ))#分割次数
    #输出:['彭于晏', '胡歌
    和在下
    都很帅']
    更多关于split方法请点击这里

    连接(join)

    描述

            Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串

    join()方法语法:

    str.join(sequence)
    

    参数

             sequence -- 要连接的元素序列

    返回值

             返回通过指定字符连接序列中元素后生成的新字符串

    str.join(元组、列表、字典、字符串) 之后生成的只能是字符串。

    所以很多地方很多时候生成了元组、列表、字典后,可以用 join() 来转化为字符串

    list=['彭于晏', '胡歌', '和在下', '都很帅']
    print('-'.join(list))
    #输出:彭于晏-胡歌-和在下-都很帅
    print('+'.join(list))
    #输出:彭于晏+胡歌+和在下+都很帅
    print(''.join(list))
    #输出:彭于晏胡歌和在下都很帅

     字典只对键进行连接

    seq = {'hello':'nihao','good':2,'boy':3,'doiido':4}
    print('-'.join(seq))#字典只对键进行连接
    #输出:hello-good-boy-doiido
    更多关于join方法请点击这里

    元组(tuple)

    元组其实跟列表差不多,可以参考列表的操作,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表,它只有2个方法,一个是count,一个是index

    定义元组:

    统计

    name=('彭于晏','胡歌','在下','胡歌','胡歌','胡歌')
    a=name.count('胡歌')#统计'胡歌'在列表里出现的次数
    print(a)
    #输出:4
    View Code

    获取下标

    name=('彭于晏','胡歌','在下')
    a=name.index('在下')#找出'在下'的下标索引值
    print(a)
    #输出:2
    View Code
    更多关于元组请点击这里

    字典(Dictionary)

    字典是另一种可变容器模型,且可存储任意类型对象。

    字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:

    d = {key1 : value1, key2 : value2 }
    

    键:一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一

    值:可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组

    增加

    dic={'':'姚明','':'王思聪','':'在下'}#定义一个列表
    dic['屌丝']='正在看的你'   #增加一对键值对
    print(dic)
    #输出:{'高': '姚明', '富': '王思聪', '帅': '在下', '屌丝': '正在看的你'}
    View Code

    删除

    dic={'':'姚明','':'王思聪','':'在下','你你你':'是多余的'}#定义一个列表
    del dic['你你你']#删除该键值对
    print(dic)
    #输出:{'富': '王思聪', '帅': '在下', '高': '姚明'}
    View Code

    修改

    dic={'':'姚明','':'王思聪','':'在下'}#定义一个列表
    dic['']='在下'#修改值
    dic['']='在下'
    print(dic)
    #输出:{'帅': '在下', '富': '在下', '高': '在下'}
    View Code

    清空

    dic={'':'姚明','':'王思聪','':'在下'}#定义一个列表
    dic.clear()#清空字典内所有内容
    print(dic)
    #输出:{}
    View Code

    遍历

    dic={'':'姚明','':'王思聪','':'在下'}#定义一个列表
    for k in dic:
        print("dic[%s] ="%k, dic[k])
    #  输出:
    #       dic[高] = 姚明
    #       dic[富] = 王思聪
    #       dic[帅] = 在下
    View Code

    字典items()的使用 

    dic={'':'姚明','':'王思聪','':'在下'}#定义一个字典
    print(dic.items())#每个元素是一个key和value组成的元组,以列表的方式输出
    #输出:dict_items([('高', '姚明'), ('富', '王思聪'), ('帅', '在下')])
    View Code

    调用items()实现字典的遍历

    dic={'':'姚明','':'王思聪','':'在下'}#定义一个字典
    for (k, v) in dic.items(): #k用来遍历键,v用来遍历值
        print("dict[%s] =" % k, v)
    #输出:
    #     dict[高] = 姚明
    #     dict[帅] = 在下
    #     dict[富] = 王思聪
    View Code

    使用列表、字典作为字典的值

    dic={'':'姚明','':{'':'姚明','':'王思聪','':'在下'},'':[1,2,3,4,5,6,7,8,9]}#定义一个字典
    
    print(dic[''])
    #输出:姚明
    
    print(dic[''][1])
    #输出:明
    
    print(dic[''])
    #输出:{'富': '王思聪', '高': '姚明', '帅': '在下'}
    
    print(dic[''][''])
    #输出:在下
    
    print(dic[''])
    #输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    print(dic[''][4])
    #输出:5
    View Code

    输出key和value的列表

    dic={'':'姚明','':{'':'姚明','':'王思聪','':'在下'},'':[1,2,3,4,5,6,7,8,9]}#定义一个字典
    
    print(dic.keys())#输出key的列表
    #输出:dict_keys(['帅', '富', '高'])
    
    print(dic.values())#输出value的列表
    #输出:dict_values(['姚明', [1, 2, 3, 4, 5, 6, 7, 8, 9], {'高': '姚明', '帅': '在下', '富': '王思聪'}])
    View Code

    字典中元素的获取方法get

    dict.get(key, default=None)返回指定键的值,如果值不在字典中返回default值

    dic={'':'姚明','':{'':'姚明','':'王思聪','':'在下'},'':[1,2,3,4,5,6,7,8,9]}#定义一个字典
    a=dic.get('')#返回指定键的值,如果值不在字典中返回default值
    print(a)
    #输出:{'帅': '在下', '富': '王思聪', '高': '姚明'}
    View Code

    get()的等价语句

    D = {"key1" : "value1", "key2" : "value2"}
    if "key1" in D:
        print(D["key1"]) 
    else:
        print( "None")
    

    字典的更新dict.update(dict2),把字典dict2的键/值对更新(增添)到dict里

    dic={"a" : "apple", "b" : "banana"}
    print(dic)
    #输出:{'a': 'apple', 'b': 'banana'}
    dic2 = {"c": "grape", "d": "orange"}
    dic.update(dic2)
    print(dic)
    #输出:{'c': 'grape', 'a': 'apple', 'd': 'orange', 'b': 'banana'}
    View Code

    dict.udpate()的等价语句

    D = {"key1" : "value1", "key2" : "value2"}
    E = {"key3" : "value3", "key4" : "value4"}
    for k in E:
        D[k] = E[k]
    print (D)
    

     设置默认值dict.setdefault(key, default=None),和get()类似, 但如果键不存在于字典中,将会添加键并将值设为 None

    dict = {}
    dict.setdefault("a")#如果键不存在于字典中,将会添加键并将值设为 None
    print(dict)
    #输出:{'a': None}
    dict["a"] = "apple"
    dict.setdefault("a","default")
    print(dict)
    #输出:{'a': 'apple'}
    View Code

     调用内置的sorted() 函数对字典进行排序

    sorted() 函数对所有可迭代的对象进行排序操作(什么叫可迭代?)

    sort 与 sorted 区别:
    
    sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
    
    list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作

    sorted 语法:

    sorted(iterable[, cmp[, key[, reverse]]])
    

    参数说明:

    iterable -- 可迭代对象 cmp -- 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0 key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序 reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)

    #调用sorted()排序
    dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
    #按照key排序
    print(sorted(dict.items(), key=lambda d: d[0]))
    #输出:[('a', 'apple'), ('b', 'grape'), ('c', 'orange'), ('d', 'banana')]
    
    #按照value排序
    print(sorted(dict.items(), key=lambda d: d[1]))
    #输出:[('a', 'apple'), ('d', 'banana'), ('b', 'grape'), ('c', 'orange')]

    这里面的表达式是什么意思?lambda是 什么 ?

    字典的深浅拷贝

    在说深浅拷贝之前,先要理解所谓的赋值符号‘=’到底意味着什么?

    python中的深拷贝和浅拷贝和java里面的概念是一样的,所谓浅拷贝就是对引用的拷贝,所谓深拷贝就是对对象的资源的拷贝。
    首先,对赋值操作我们要有以下认识:

    1 赋值是将一个对象的地址赋值给一个变量,让变量指向该地址( 旧瓶装旧酒 )。
    2 修改不可变对象(str、tuple)需要开辟新的空间
    3 修改可变对象(list等)不需要开辟新的空间

    浅拷贝仅仅复制了容器中元素的地址

    a=['hello',[1,2,3]]
    b=a[:]    #这里相当于把a拷贝给b(当然这里是浅拷贝,原因见下面)
    print(id(a))
    #输出:17760392
    print(id(b))
    #输出:17783112             看,a和b有不一样的地址,说明内存是重新开了一个空间来存储列表b,继续往下
    print([id(x) for x in a])
    #输出:[8107376, 8129096]
    print([id(x) for x in b])
    #输出:[8107376, 8129096]   看,列表里两个元素的地址是没有变的,或者说这种拷贝方式仅仅拷贝了列表里元素的地址
    浅拷贝是在另一块地址中创建一个新的变量或容器,但是容器内的元素的地址均是源对象的元素的地址的拷贝。
    也就是说新的容器中指向了旧的元素( 新瓶装旧酒 )这里新的容器可以只列表或字典等

    深拷贝,完全拷贝了一个副本,容器内部元素地址都不一样(嗯,不太对哦)

    from copy import deepcopy
    a=['hello',[1,2,3]]
    b=deepcopy(a)   #这里相当于把a拷贝给b(当然这里是深拷贝,原因见下面)
    print(id(a))
    #输出:12165320
    print(id(b))
    #输出:12165832             看,a和b有不一样的地址,说明内存是重新开了一个空间来存储列表b,好,继续往下
    print([id(x) for x in a])
    #输出:[7124112, 12166728]
    print([id(x) for x in b])
    #输出:[7124112, 12166792]   看,这里有意思了,原本我以为都会变的,里面所有元素全部重新开辟地址来存储,但是,并不是
    #                            对于元素'hello'为不可变类型,并没有开辟新的地址
    #                            对于元素[1,2,3]为可变类型  ,则重新开辟新的地址,为什么要这样?

    为什么对于可变类型的元素要重新开辟地址 ,而不可变元素则不用?以下是我的理解 

    对于不可变元素,既然叫不可变,意味着是不能改变的,如果‘改变’是指在新的地址下存储新的元素。
    对于深拷贝,目的就是要创建一个玩玩全全独立的副本,就意味着所有的一切都应该在新的地址上。
    1、对于列表或者字典本身,深拷贝结果下,地址是改变了的,也就是说瓶子是换新了的 。
    2、所有可变类型的元素也是有了新的地址的。
    3、对于不可变类型的元素,地址没有变,那岂不是相互有影响?不,如果你改变了不可变类型,就会在新的地址下储存新的数据了,也是没有影响的。
    反正 我懂了
    深拷贝是在另一块地址中创建一个新的变量或容器,同时容器内的元素的地址也是新开辟的,仅仅是值相同而已,是完全的副本。
    也就是说( 新瓶装新酒 )(嗯,貌似和我说的不太一样哦,还要考虑可变还是不可变,当然反正没什么影响)

    字典的浅拷贝

    dict= {"a" : "apple", "b" : "grape"}
    dict2 = {"c" : "orange", "d" : "banana"}
    dict2 = dict.copy()
    print(dict2)
    #输出:{'a': 'apple', 'b': 'grape'}
    View Code
    #字典的深拷贝
    import copy
    dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
    dict2 = copy.deepcopy(dict)#深拷贝,玩玩全全独立的副本
    dict3 = dict.copy()        #浅拷贝
    dict2["b"]["g"] = "orange"
    print(dict)
    #输出:{'b': {'g': 'grape', 'o': 'orange'}, 'a': 'apple'}  ,dict和原来一样,并没有改变,因为dict2是深拷贝完全独立的 
    dict3["b"]["g"] = "orange"
    print(dict)
    #输出:{'b': {'g': 'orange', 'o': 'orange'}, 'a': 'apple'},浅拷贝

     更多关于字典请点击这里

     集合 (set)

    集合是一个无序的,不重复的数据组合,它的主要作用如下:

    • 去重,把一个列表变成集合,就自动去重了
    • 关系测试,测试两组数据之前的交集、差集、并集等关系

    要创建一个set,需要提供一个list作为输入集合

    创建集合

    s =set([3, 5, 9,3,5,3,410])  # 创建一个数值集合
    print(s)
    #输出:{9, 410, 3, 5},已经自动去重t
    
    t = set("Hello")  # 创建一个唯一字符的集合
    print(t)
    #输出:{'o', 'l', 'H', 'e'}

    增加

    s =set([3, 5, 9,3,5,3,410])  # 创建一个数值集合
    print(s)
    #输出:{9, 410, 3, 5},已经自动去重t
    
    t = set("Hello")  # 创建一个唯一字符的集合
    print(t)
    #输出:{'o', 'l', 'H', 'e'}
    
    t.add('x')            # 添加一项
    print(t)
    #输出:{'l', 'o', 'e', 'H', 'x'}
    
    s.update([10,37,42])  # 在s中添加多项
    print(s)
    #输出:{3, 5, 37, 9, 10, 42, 410}

    删除

    t = set("Hello")  # 创建一个唯一字符的集合
    print(t)
    #输出:{'o', 'l', 'H', 'e'}
    t.remove('H')#使用remove()可以删除一项
    print(t)
    #输出:{'l', 'e', 'o'}

    长度

    t = set("Hello")  # 创建一个唯一字符的集合
    print(len(t))#计算集合里元素的个数,当然,是去重后的
    #输出:4

    包含

    t = set("Hello")  # 创建一个唯一字符的集合
    print('x' in t)  #判断x是否在集合t中
    #输出:False
    
    print('x' not in t )#判断x是否不在集合t中
    #输出:True

    子集

    t = set("Hello")  # 创建一个唯一字符的集合
    tt = set('Hello world')
    print(t <= tt)  # 判断t集合里的元素是否包含于集合tt
    print(tt >= t)  # 判断集合tt是否包含集合t
    print(t.issubset(tt))  # 判断t集合里的元素是否包含于集合tt
    print(tt.issuperset(t))# 判断集合tt是否包含集合t
    #输出:True
    #输出:True
    #输出:True
    #输出:True

     

    
    
  • 相关阅读:
    Ubuntu 虚拟机安装几点细节整理
    jQuery与IE兼容性问题处理
    Excel已损坏,无法打开
    应对刷新闪烁问题
    ArcGIS鼠标滚轮方向之代码篇
    ChartControl控件0和null的效果
    多个组件联合打印输出——PrintableComponentLink
    Skyline中加载WMTS地图
    访问天地图WMTS服务的正确姿势
    超图不支持JPEG格式的WMTS服务
  • 原文地址:https://www.cnblogs.com/LUOyaXIONG/p/9848666.html
Copyright © 2020-2023  润新知