• Python数据类型及其方法详解


    Python数据类型及其方法详解

    我们在学习编程语言的时候,都会遇到数据类型,这种看着很基础也不显眼的东西,却是很重要,本文介绍了python的数据类型,并就每种数据类型的方法作出了详细的描述,可供知识回顾。

    一、整型和长整型

    整型:数据是不包含小数部分的数值型数据,比如我们所说的1、2、3、4、122,其type为"int"
    长整型:也是一种数字型数据,但是一般数字很大,其type为"long"
    在python2中区分整型和长整型,在32位的机器上,取值范围是-2147483648~2147483647,超出范围的为长整型,在64位的机器上,取值范围为-9223372036854775808~9223372036854775807(通常也与python的解释器的位数有关)。
    在python3中,不存在整型和长整型之分,只有整型。
    举个例子:
    python2中
    number = 123
    print (type(number))
    number2 = 2147483647
    print (type(number2))
    number2 = 2147483648    #我们会看到超过2147483647这个范围,在py2中整形就会变成长整形了
    print (type(number2))
    #运行结果
    <type 'int'>
    <type 'int'>
    <type 'long'>
    #python3中
    number = 123
    print (type(number))
    number2 = 2147483648   
    print (type(number2))    #在python3中并不会
    #运行结果
    <class 'int'>
    <class 'int'>
    View Code

    常用的method的如下:

    .bit_length()

    取最短bit位数

      def bit_length(self): # real signature unknown; restored from __doc__
            """
            int.bit_length() -> int
            
            Number of bits necessary to represent self in binary.
            >>> bin(37)
            '0b100101'
            >>> (37).bit_length()
            6
            """
            return 0
    View Code

    举个例子:

    number = 12  #1100 
    print(number.bit_length())
    #运行结果
    4
    View Code

     二、浮点型

     浮点型可以看成就是小数,type为float。

    #浮点型
    number = 1.1
    print(type(number))
    #运行结果
    <class 'float'>
    View Code

     常用method的如下:

    .as_integer_ratio()

    返回元组(X,Y),number = k ,number.as_integer_ratio() ==>(x,y) x/y=k

        def as_integer_ratio(self): # real signature unknown; restored from __doc__
            """
            float.as_integer_ratio() -> (int, int)
            
            Return a pair of integers, whose ratio is exactly equal to the original
            float and with a positive denominator.
            Raise OverflowError on infinities and a ValueError on NaNs.
            
            >>> (10.0).as_integer_ratio()
            (10, 1)
            >>> (0.0).as_integer_ratio()
            (0, 1)
            >>> (-.25).as_integer_ratio()
            (-1, 4)
            """
            pass
    View Code

     举个例子

    number = 0.25
    print(number.as_integer_ratio())
    #运行结果
    (1, 4)
    View Code

    .hex()

     以十六进制表示浮点数

        def hex(self): # real signature unknown; restored from __doc__
            """
            float.hex() -> string
            
            Return a hexadecimal representation of a floating-point number.
            >>> (-0.1).hex()
            '-0x1.999999999999ap-4'
            >>> 3.14159.hex()
            '0x1.921f9f01b866ep+1'
            """
            return ""
    View Code

     举个例子

    number = 3.1415
    print(number.hex())
    #运行结果
    0x1.921cac083126fp+1
    View Code

    .fromhex()

    将十六进制小数以字符串输入,返回十进制小数

        def fromhex(string): # real signature unknown; restored from __doc__
            """
            float.fromhex(string) -> float
            
            Create a floating-point number from a hexadecimal string.
            >>> float.fromhex('0x1.ffffp10')
            2047.984375
            >>> float.fromhex('-0x1p-1074')
            -5e-324
            """
    View Code

    举个例子

    print(float.fromhex('0x1.921cac083126fp+1'))
    #运行结果
    3.1415
    View Code

    .is_integer()

    判断小数是不是整数,比如3.0为一个整数,而3.1不是,返回布尔值

        def is_integer(self, *args, **kwargs): # real signature unknown
            """ Return True if the float is an integer. """
            pass
    View Code

    举个例子

    number = 3.1415
    number2 = 3.0
    print(number.is_integer())
    print(number2.is_integer())
    #运行结果
    False
    True
    View Code

    三、字符类型

    字符串就是一些列的字符,在Python中用单引号或者双引号括起来,多行可以用三引号。

    name = 'my name is Frank'
    name1 = "my name is Frank"
    name2 = '''my name is Frank
    I'm 23 years old,      
           '''
    print(name)
    print(name1)
    print(name2)
    #运行结果
    my name is Frank
    my name is Frank
    my name is Frank
    I'm 23 years old  
    View Code

    常用method的如下:

    .capitalize()

    字符串首字符大写

      def capitalize(self): # real signature unknown; restored from __doc__
            """
            S.capitalize() -> str
            
            Return a capitalized version of S, i.e. make the first character
            have upper case and the rest lower case.
            """
            return ""
    View Code

    举个例子

    name = 'my name is Frank'
    #运行结果
    My name is frank
    View Code

    .center()

    字符居中,指定宽度和填充字符(默认为空格)

      def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            S.center(width[, fillchar]) -> str
            
            Return S centered in a string of length width. Padding is
            done using the specified fill character (default is a space)
            """
            return ""
    View Code

    举个例子

    flag = "Welcome Frank"
    print(flag.center(50,'*'))
    #运行结果
    ******************Welcome Frank*******************
    View Code

    .count()

    计算字符串中某个字符的个数,可以指定索引范围

        def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = 'aaababbcccaddadaddd'
    print(flag.count('a'))
    print(flag.count('a',0,3))
    #运行结果
    7
    3
    View Code

    .encode()

    编码,在python3中,str默认是unicode数据类型,可以将其编码成bytes数据

        def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
            """
            S.encode(encoding='utf-8', errors='strict') -> bytes
            
            Encode S using the codec registered for encoding. Default encoding
            is 'utf-8'. 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 can handle UnicodeEncodeErrors.
            """
            return b""
    View Code

    举个例子

    flag = 'aaababbcccaddadaddd'
    print(flag.encode('utf8'))
    #运行结果
    b'aaababbcccaddadaddd'
    View Code

    .endswith()

    判断字符串结尾是否是某个字符串和字符,可以通过索引指定范围

       def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = 'aaababbcccaddadaddd'
    print(flag.endswith('aa'))
    print(flag.endswith('ddd'))
    print(flag.endswith('dddd'))
    print(flag.endswith('aaa',0,3))
    print(flag.endswith('aaa',0,2))
    #运行结果
    False
    True
    False
    True
    False
    View Code

    .expandtabs()

    把制表符tab(" ")转换为空格

      def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
            """
            S.expandtabs(tabsize=8) -> str
            
            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 ""
    View Code

    举个例子

    flag = "	hello python!"
    print(flag)
    print(flag.expandtabs())   #默认tabsize=8
    print(flag.expandtabs(20))
    #运行结果
        hello python!             #一个tab,长度为4个空格
            hello python!         #8个空格
                        hello python!    #20个空格
    View Code

    .find()

    查找字符,返回索引值,可以通过指定索引范围内查找,查找不到返回-1

        def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "hello python!"
    print(flag.find('e'))
    print(flag.find('a'))
    print(flag.find('h',4,-1))
    #运行结果
    1
    -1
    9
    View Code

    .format()

    格式化输出,使用"{}"符号作为操作符。

    def format(self, *args, **kwargs): # known special case of str.format
            """
            S.format(*args, **kwargs) -> str
            
            Return a formatted version of S, using substitutions from args and kwargs.
            The substitutions are identified by braces ('{' and '}').
            """
            pass
    View Code

    举个例子

    #位置参数
    flag = "hello {0} and {1}!"
    print(flag.format('python','php'))
    flag = "hello {} and {}!"
    print(flag.format('python','php'))
    #变量参数
    flag = "{name} is {age} years old!"
    print(flag.format(name='Frank',age = 23))
    #结合列表
    infor=["Frank",23]
    print("{0[0]} is {0[1]} years old".format(infor))
    #运行结果
    hello python and php!
    hello python and php!
    Frank is 23 years old!
    Frank is 23 years old
    View Code

    .format_map()

    格式化输出

     def format_map(self, mapping): # real signature unknown; restored from __doc__
            """
            S.format_map(mapping) -> str
            
            Return a formatted version of S, using substitutions from mapping.
            The substitutions are identified by braces ('{' and '}').
            """
            return ""
    View Code

    举个例子

    people={
        'name':['Frank','Caroline'],
        'age':['23','22'],
    }
    print("My name is {name[0]},i am {age[1]} years old !".format_map(people))
    #运行结果
    My name is Frank,i am 22 years old !
    View Code

    .index()

    根据字符查找索引值,可以指定索引范围查找,查找不到会报错

     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.index(sub[, start[, end]]) -> int
            
            Like S.find() but raise ValueError when the substring is not found.
            """
            return 0
    View Code

    举个例子

    flag = "hello python!"
    print(flag.index("e"))
    print(flag.index("o",6,-1))
    #运行结果
    1
    10
    View Code

    .isalnum()

    判断是否是字母或数字组合,返回布尔值

    def isalnum(self): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "hellopython"
    flag1 = "hellopython22"
    flag2 = "hellopython!!"
    flag3 = "!@#!#@!!@"
    print(flag.isalnum())
    print(flag1.isalnum())
    print(flag2.isalnum())
    print(flag3.isalnum())
    #运行结果
    True
    True
    False
    False
    View Code

    .isalpha()

    判断是否是字母组合,返回布尔值

     def isalpha(self): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "hellopython"
    flag1 = "hellopython22"
    print(flag.isalpha())
    print(flag1.isalpha())
    #运行结果
    True
    False
    View Code

    .isdecimal()

    判断是否是一个十进制正整数,返回布尔值

      def isdecimal(self): # real signature unknown; restored from __doc__
            """
            S.isdecimal() -> bool
            
            Return True if there are only decimal characters in S,
            False otherwise.
            """
            return False
    View Code

    举个例子

    number = "1.2"
    number1 = "12"
    number2 = "-12"
    number3 = "1222"
    print(number.isdecimal())
    print(number1.isdecimal())
    print(number2.isdecimal())
    print(number3.isdecimal())
    #运行结果
    False
    True
    False
    True
    View Code

    isdigit()

    判断是否是一个正整数,返回布尔值,与上面isdecimal类似

      def isdigit(self): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    number = "1.2"
    number1 = "12"
    number2 = "-12"
    number3 = "11"
    print(number.isdigit())
    print(number1.isdigit())
    print(number2.isdigit())
    print(number3.isdigit())
    #运行结果
    False
    True
    False
    True
    View Code

    .isidentifier()

    判断是否为python中的标识符

     def isidentifier(self): # real signature unknown; restored from __doc__
            """
            S.isidentifier() -> bool
            
            Return True if S is a valid identifier according
            to the language definition.
            
            Use keyword.iskeyword() to test for reserved identifiers
            such as "def" and "class".
            """
            return False
    View Code

    举个例子

    flag = "cisco"
    flag1 = "1cisco"
    flag2 = "print"
    print(flag.isidentifier())
    print(flag1.isidentifier())
    print(flag2.isidentifier())
    #运行结果
    True
    False
    True
    View Code

    .islower()

     判断字符串中的字母是不是都是小写,返回布尔值

        def islower(self): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "cisco"
    flag1 = "cisco222"
    flag2 = "Cisco"
    print(flag.islower())
    print(flag1.islower())
    print(flag2.islower())
    #运行结果
    True
    True
    False
    View Code

    .isnumeric()

    判断是否为数字,这个很强大,中文字符,繁体字数字都可以识别

     def isnumeric(self): # real signature unknown; restored from __doc__
            """
            S.isnumeric() -> bool
            
            Return True if there are only numeric characters in S,
            False otherwise.
            """
            return False
    View Code

    举个例子

    number = "123"
    number1 = ""
    number2 = ""
    number3 = "123q"
    number4 = "1.1"
    print(number.isnumeric())
    print(number1.isnumeric())
    print(number2.isnumeric())
    print(number3.isnumeric())
    print(number4.isnumeric())
    #运行结果
    True
    True
    True
    False
    False
    View Code

    .isprintable()

    判断引号里面的是否都是可打印的,返回布尔值

       def isprintable(self): # real signature unknown; restored from __doc__
            """
            S.isprintable() -> bool
            
            Return True if all characters in S are considered
            printable in repr() or S is empty, False otherwise.
            """
            return False
    View Code

    举个例子

    flag = "
    123"
    flag1 = "	"
    flag2 = "123"
    flag3 = r"
    123"    # r 可以是转义字符失效
    print(flag.isprintable())     #
    不可打印
    print(flag1.isprintable())    #	不可打印
    print(flag2.isprintable())
    print(flag3.isprintable())
    #运行结果
    False
    False
    True
    True
    View Code

    .isspace()

    判断字符串里面都是空白位,空格或者tab,返回布尔值

      def isspace(self): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = '    '     #4个空格
    flag1 = '        '#2个tab
    print(flag.isspace())
    print(flag1.isspace())
    #运行结果
    True
    True
    View Code

    .istitle()

    判断字符串里面的字符是否都是大写开头,返回布尔值

      def isspace(self): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "Welcome Frank"
    flag1 = "Welcome frank"
    print(flag.istitle())
    print(flag1.istitle())
    #运行结果
    True
    False
    View Code

    .isupper()

    判断是否都是字符串里的字母都是大写

        def isupper(self): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "WELCOME1"
    flag1 = "Welcome1"
    print(flag.isupper())
    print(flag1.isupper())
    #运行结果
    True
    False
    View Code

    .join()

    将字符串以指定的字符连接生成一个新的字符串

      def join(self, iterable): # real signature unknown; restored from __doc__
            """
            S.join(iterable) -> str
            
            Return a string which is the concatenation of the strings in the
            iterable.  The separator between elements is S.
            """
            return ""
    View Code

    举个例子

    flag = "welcome"
    print("#".join(flag))
    #运行结果
    w#e#l#c#o#m#e
    View Code

    .ljust()

    左对齐,可指定字符宽度和填充字符

       def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            S.ljust(width[, fillchar]) -> str
            
            Return S left-justified in a Unicode string of length width. Padding is
            done using the specified fill character (default is a space).
            """
            return ""
    View Code

    举个例子

    flag = "welcome"
    print(flag.ljust(20,"*"))
    #运行结果
    welcome*************
    View Code

    .rjust()

    右对齐,可指定字符宽度和填充字符

        def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            S.rjust(width[, fillchar]) -> str
            
            Return S right-justified in a string of length width. Padding is
            done using the specified fill character (default is a space).
            """
            return ""
    View Code

    举个例子

    flag = "welcome"
    print(flag.rjust(20,"*"))
    #运行结果
    *************welcome
    View Code

    .lower()

    对字符串里的所有字母转小写

        def lower(self): # real signature unknown; restored from __doc__
            """
            S.lower() -> str
            
            Return a copy of the string S converted to lowercase.
            """
            return ""
    View Code

    举个例子

    flag = "WELcome"
    #运行结果
    welcome
    View Code

    .upper()

    对字符串里的所有字母转大写

        def upper(self): # real signature unknown; restored from __doc__
            """
            S.upper() -> str
            
            Return a copy of S converted to uppercase.
            """
            return ""
    View Code

    举个例子

    flag = "WELcome"
    print(flag.upper())
    #运行结果
    WELCOME
    View Code

    .title()

    对字符串里的单词进行首字母大写转换

        def title(self): # real signature unknown; restored from __doc__
            """
            S.title() -> str
            
            Return a titlecased version of S, i.e. words start with title case
            characters, all remaining cased characters have lower case.
            """
            return ""
    View Code

    举个例子

    flag = "welcome frank"
    print(flag.title())
    #运行结果
    Welcome Frank
    View Code

    .lstrip()

    默认去除左边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。

      def lstrip(self, chars=None): # real signature unknown; restored from __doc__
            """
            S.lstrip([chars]) -> str
            
            Return a copy of the string S with leading whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            """
            return ""
    View Code

    举个例子

    flag = "     welcome frank"
    flag1 = "@@@@welcome frank"
    print(flag.lstrip())
    print(flag.lstrip("@"))
    print(flag.lstrip("@").lstrip())
    #运行结果
    welcome frank
         welcome frank
    welcome frank
    View Code

    .rstrip()

    默认去除右边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。

     def rstrip(self, chars=None): # real signature unknown; restored from __doc__
            """
            S.rstrip([chars]) -> str
            
            Return a copy of the string S with trailing whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            """
            return ""
    View Code

    举个例子

    flag = "welcome frank    "
    flag1 = "welcome frank@@@@"
    # print(flag.title())
    print(flag.rstrip())
    print(flag.rstrip("@"))
    print(flag.rstrip("@").rstrip())
    #运行结果
    welcome frank
    welcome frank    #右边有4个空格
    welcome frank
    View Code

    .strip()

    默认去除两边空白字符,可指定去除的字符,去除指定的字符后,会被空白占位。

        def strip(self, chars=None): # real signature unknown; restored from __doc__
            """
            S.strip([chars]) -> str
            
            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.
            """
            return ""
    View Code

    举个例子

    flag = "    welcome frank    "
    flag1 = "@@@@welcome frank@@@@"
    # print(flag.title())
    print(flag.strip())
    print(flag.strip("@"))
    print(flag.strip("@").strip())
    #运行结果
    welcome frank
        welcome frank    #右边有4个空格
    welcome frank
    View Code

    .maketrans()和translate()

    创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。两个字符串的长度必须相同,为一一对应的关系。

       def maketrans(self, *args, **kwargs): # real signature unknown
            """
            Return a translation table usable for str.translate().
            
            If there is only one argument, it must be a dictionary mapping Unicode
            ordinals (integers) or characters to Unicode ordinals, strings or None.
            Character keys will be then converted to ordinals.
            If there are two arguments, they must be strings of equal length, and
            in the resulting dictionary, each character in x will be mapped to the
            character at the same position in y. If there is a third argument, it
            must be a string, whose characters will be mapped to None in the result.
            """
            pass
    View Code
      def translate(self, table): # real signature unknown; restored from __doc__
            """
            S.translate(table) -> str
            
            Return a copy of the string S in which each character has been mapped
            through the given translation table. The table must implement
            lookup/indexing via __getitem__, for instance a dictionary or list,
            mapping Unicode ordinals to Unicode ordinals, strings, or None. If
            this operation raises LookupError, the character is left untouched.
            Characters mapped to None are deleted.
            """
            return ""
    View Code

    举个例子

    intab = "aeiou"
    outtab = "12345"
    trantab = str.maketrans(intab, outtab)
    str = "this is string example....wow!!!"
    print (str.translate(trantab))
    #运行结果
    th3s 3s str3ng 2x1mpl2....w4w!!!
    View Code

    .partition()

    以指定字符分割,返回一个元组

     def partition(self, sep): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "welcome"
    print(flag.partition("e"))
    #运行结果
    ('w', 'e', 'lcome')
    View Code

    .replace()

    将指定的字符替换为新的字符,可指定替换的个数

        def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
            """
            S.replace(old, new[, count]) -> str
            
            Return a copy of 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 ""
    View Code

    举个例子

    flag = "welcome frank ,e.."
    print(flag.replace("e","z"))
    print(flag.replace("e","z",1))
    #运行结果
    wzlcomz frank ,z..
    wzlcome frank ,e..
    View Code

    .rfind()

    返回字符串第一次出现的位置,从右向左差,返回索引值,若没有,则返回-1,可根据索引范围查找

       def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "welcome frank ,e.."
    print(flag.rfind("e"))
    print(flag.rfind("x"))
    print(flag.rfind("e",0,3))
    #运行结果
    15
    -1
    1
    View Code

    .rindex()

     查找字符索引值,从右向左,返回索引值,与rfind类似,查找不到会报错

     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.rindex(sub[, start[, end]]) -> int
            
            Like S.rfind() but raise ValueError when the substring is not found.
            """
            return 0
    View Code

    举个例子

    flag = "welcome frank ,e.."
    print(flag.rindex("e"))
    print(flag.rindex("e",0,3))
    #运行结果
    15
    1
    View Code

    .rpartition()

    以指定字符从右向左分割,只分割一次,返回元组,若没有指定的字符,则在返回的元组前面加两个空字符串

        def rpartition(self, sep): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    flag = "welcome frank ,e.."
    print(flag.rpartition("e"))
    print(flag.rpartition("x"))
    #运行结果
    ('welcome frank ,', 'e', '..')
    ('', '', 'welcome frank ,e..')
    View Code

    .split()

    分割,可以以指定的字符分割,可指定分割的次数,默认从左向右分割,与partition不同的是,split分割后会删除指定的字符,默认以空格为分割符,返回元组。

        def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
            """
            S.split(sep=None, maxsplit=-1) -> list of strings
            
            Return a list of the words in 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 []
    View Code

    举个例子

    flag = "welcome frank, e.."
    print(flag.split())
    print(flag.split('e'))
    print(flag.split('e',1))
    #运行结果
    ['welcome', 'frank,', 'e..']
    ['w', 'lcom', ' frank, ', '..']
    ['w', 'lcome frank, e..']
    View Code

    .rsplit()

    与split类似,只是它是从右向左分

        def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
            """
            S.rsplit(sep=None, maxsplit=-1) -> list of strings
            
            Return a list of the words in 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, any whitespace string
            is a separator.
            """
            return []
    View Code

    举个例子

    flag = "welcome frank, e.."
    print(flag.rsplit())
    print(flag.rsplit('e'))
    print(flag.rsplit('e',1))
    #运行结果
    ['welcome', 'frank,', 'e..']
    ['w', 'lcom', ' frank, ', '..']
    ['welcome frank, ', '..']
    View Code

    .splitlines()

    字符串转换为列表

        def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
            """
            S.splitlines([keepends]) -> 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 []
    View Code

    举个例子

    info = "hello,my name is Frank"
    print(info.splitlines())
    #运行结果
    ['hello,my name is Frank']
    View Code

    .startswith()

    判断是否以指定字符串或字符开头,可指定索引范围,返回布尔值

     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            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
    View Code

    举个例子

    info = "hello,my name is Frank"
    print(info.startswith("he"))
    print(info.startswith("e"))
    print(info.startswith("m",6,-1))
    #运行结果
    True
    False
    True
    View Code

    .swapcase()

    将字符串中的大小写互换

       def swapcase(self): # real signature unknown; restored from __doc__
            """
            S.swapcase() -> str
            
            Return a copy of S with uppercase characters converted to lowercase
            and vice versa.
            """
            return ""
    View Code

    举个例子

    info = "Hello,My name is Frank"
    print(info.swapcase())
    #运行结果
    hELLO,mY NAME IS fRANK
    View Code

    .zfill()

    指定字符串宽度,不足的右边填“0”

        def zfill(self, width): # real signature unknown; restored from __doc__
            """
            S.zfill(width) -> str
            
            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 ""
    View Code

    举个例子

    info = "Hello,My name is Frank"
    print(info.zfill(50))
    #运行结果
    0000000000000000000000000000Hello,My name is Frank
    View Code

    四、列表

    列表是由一系列按特定顺序排列的元素组成。在python中,用方括号([]),来表示列表,并用逗号来分割其中的元素,我们来看一下简单的列表,其type为"list"

    name = ['Frank','Caroline','Bob','Saber']
    print(name)  #直接打印会将中括号、引号和逗号都打印出来
    print(name[1]) #添加索引可打印对应的值,从索引值从0开始
    print(name[-1]) #打印最后一个元素
    print(name[0:2]) #用冒号来切片,取右不取左
    print(name[-2:]) #冒号右边不写代表一直打印到最后一个
    print(name[:1]) #冒号左边不写代表从第“0”个开始打印
    View Code

     常见方法如下:

    .index()

     查找对应元素的索引值,返回索引值,可以指定索引范围来查找,查找不到会报错

        def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
            """
            L.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    View Code

     举个例子

    name = ['Frank','Caroline','Bob','Saber']
    print(name.index("Frank"))
    print(name.index("Bob",1,-1))
    #运行结果
    0
    2
    View Code

    .count()

     计算某个元素的个数

      def count(self, value): # real signature unknown; restored from __doc__
            """ L.count(value) -> integer -- return number of occurrences of value """
            return 0
    View Code

     举个例子

    name = ['Frank','Caroline','Bob','Saber','Frank']
    print(name.count('Frank'))
    #运行结果
    2
    View Code

     .append()

     在列表的最后添加元素

        def append(self, p_object): # real signature unknown; restored from __doc__
            """ L.append(object) -> None -- append object to end """
            pass
    View Code

     举个例子

    name = ['Frank','Caroline','Bob','Saber','Frank']
    name.append('Mei')
    print(name)
    #运行结果
    ['Frank', 'Caroline', 'Bob', 'Saber', 'Frank', 'Mei']
    View Code

    .clear()

     清空列表

     def clear(self): # real signature unknown; restored from __doc__
            """ L.clear() -> None -- remove all items from L """
            pass
    View Code

     举个例子

    name = ['Frank','Caroline','Bob','Saber','Frank']
    name.clear()
    print(name)
    #运行结果
    []
    View Code

     .copy()

     复制列表

       def copy(self): # real signature unknown; restored from __doc__
            """ L.copy() -> list -- a shallow copy of L """
            return []
    View Code

     举个例子

    name = ['Saber','Frank',1,2,[3,4]]
    name_cp = name.copy()
    print(name_cp)
    name[0]='Tom'
    name[3]='7'
    name[4][0]='8'
    print(name)
    print(name_cp)
    #运行结果
    ['Saber', 'Frank', 1, 2, [3, 4]]
    ['Tom', 'Frank', 1, '7', ['8', 4]]
    ['Saber', 'Frank', 1, 2, ['8', 4]]
    View Code
    我们会发现,我们给name[0]、name[3]、和name[4][0]都重新赋值了,为什么我重新赋值的name[4][0]会影响到我复制的列表的呢?
    首先我们来看一下这个复制图解:

     

    我们在复制的时候,新复制的列表都会指向被复制列表的地址空间,name[4]和name_cp[4]本身也是个列表,它们指向的是同一个列表地址空间。我们来看一下给name列表重新赋值后,地址空间的变化:

     

     重新赋值后,内存给name[3]、name[0]、name[4][0]都重新开辟了一块内存空间,name[0]指向了内存地址38703432,name[3]指向了内存地址1400943960,而name[4]还是指向37092936,但是内存地址37092936指向name[4][0]内存地址发生了变化,指向了1400944350,所以,在列表中的列表我们给它重新赋值的时候,也会改变复制列表的值,因为它们的列表里的列表都是指向同一块地址空间。那么如果我们想完全复制怎么办呢?

     可以调用函数deepcopy().

    import copy
    name = ['Saber','Frank',1,2,[3,4]]
    name_cp=copy.deepcopy(name)
    name[4][0]=5
    print(name)
    print(name_cp)
    #运行结果
    ['Saber', 'Frank', 1, 2, [5, 4]]
    ['Saber', 'Frank', 1, 2, [3, 4]]
    View Code

     

     这样会给复制后的列表中的列表重新开辟一个地址空间,然后指向列表中列表的元素的地址空间,这样你怎么改变原列表name,name_copy都不会改变。

    .extend()

     函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。

     def extend(self, iterable): # real signature unknown; restored from __doc__
            """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
            pass
    View Code

     举个例子

    name = ['Saber','Frank']
    nameto = ['Mei','Jack']
    name.extend(nameto)
    print(name)
    #运行结果
    ['Saber', 'Frank', 'Mei', 'Jack']
    View Code

    insert()

    插入元素,需要指定索引值来插入

     def insert(self, index, p_object): # real signature unknown; restored from __doc__
            """ L.insert(index, object) -- insert object before index """
            pass
    View Code

     举个例子

    name = ['Saber','Frank']
    name.insert(0,'Jack')
    print(name)
    #运行结果
    ['Jack', 'Saber', 'Frank']
    View Code

     .pop()

     弹出元素,默认弹出最后一个元素,可以指定索引,弹出对应的元素,当列表弹空或者没有指定的索引值会报错,并返回弹出的值

     def pop(self, index=None): # real signature unknown; restored from __doc__
            """
            L.pop([index]) -> item -- remove and return item at index (default last).
            Raises IndexError if list is empty or index is out of range.
            """
            pass
    View Code

    举个例子

    name = ['Saber','Frank','Caroline','Jack']
    name.pop()
    print(name)
    name = ['Saber','Frank','Caroline','Jack']
    name.pop(1)
    print(name)
    #运行结果
    ['Saber', 'Frank', 'Caroline']
    ['Saber', 'Caroline', 'Jack']
    View Code

    .remove()

    移除指定的元素

    def remove(self, value): # real signature unknown; restored from __doc__
            """
            L.remove(value) -> None -- remove first occurrence of value.
            Raises ValueError if the value is not present.
            """
            pass
    View Code

     举个例子

    name = ['Saber','Frank','Caroline','Jack']
    name.remove('Frank')
    print(name)
    #运行结果
    ['Saber', 'Caroline', 'Jack']
    View Code

    .reverse()

     列表反转,永久修改

        def reverse(self): # real signature unknown; restored from __doc__
            """ L.reverse() -- reverse *IN PLACE* """
            pass
    View Code

     举个例子

    name = ['Saber','Frank','Caroline','Jack']
    name.reverse()
    print(name)
    #运行结果
    ['Jack', 'Caroline', 'Frank', 'Saber']
    View Code

    .sort()

    对列表进行排序,永久修改,如果列表中同时存在不同类型的数据,则不能排序,比如含有整型和字符串,传递reverse=True可以倒着排序。

     def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
            """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
            pass
    View Code

    举个例子

    name = ['Saber','Frank','Caroline','Jack','1','abc','xyz']
    name.sort()
    print(name)
    name.sort(reverse=True)
    print(name)
    #运行结果
    ['1', 'Caroline', 'Frank', 'Jack', 'Saber', 'abc', 'xyz']
    ['xyz', 'abc', 'Saber', 'Jack', 'Frank', 'Caroline', '1']
    number = [1,2,3,42,12,32,43,543]
    number.sort()
    print(number)
    number.sort(reverse=True)
    print(number)
    #运行结果
    [1, 2, 3, 12, 32, 42, 43, 543]
    [543, 43, 42, 32, 12, 3, 2, 1]
    View Code

    五、元组

    元组和列表类似,不同的是元组的元素是不能修改的,使用小括号"()"括起来,用逗号","分开,其type为tuple

    number = (1,2,2,2,1)
    print(type(number))
    print(number[0])
    print(number[-1])
    print(number[1:])
    #运行结果
    <class 'tuple'>
    1
    1
    (2, 2, 2, 1)
    View Code

    常见方法如下:

    .count()

    计算指定元素的个数

       def count(self, value): # real signature unknown; restored from __doc__
            """ T.count(value) -> integer -- return number of occurrences of value """
            return 0
    View Code

    举个例子

    number = (1,2,2,2,1)
    print(number.count(2))
    #运行结果
    3
    View Code

    .index()

    查找指定元素的索引,可以指定索引范围来查找

     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
            """
            T.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    View Code

    举个例子

    number = (1,2,2,2,1)
    print(number.index(2))
    print(number.index(2,2,-1))
    #运行结果
    1
    2
    View Code

    六、集合

    集合是一系列无序的元素组成,所有你不能使用索引值,在打印的时候,元组是自然排序,天然去重的,其type为set

    number = {1,2,3,4,4,5,6}
    number1 = {1,6,2,1,8,9,10}
    print(number)
    print(number1)
    #运行结果
    {1, 2, 3, 4, 5, 6}
    {1, 2, 6, 8, 9, 10}
    View Code

    常用方法如下

    .remove()

    移除指定的元素

      def remove(self, *args, **kwargs): # real signature unknown
            """
            Remove an element from a set; it must be a member.
            
            If the element is not a member, raise a KeyError.
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,4,5,6}
    print(number)
    number.remove(1)
    print(number)
    #运行结果
    {1, 2, 3, 4, 5, 6}
    {2, 3, 4, 5, 6}
    View Code

    .pop()

    弹出排序过后的第一个元素

        def pop(self, *args, **kwargs): # real signature unknown
            """
            Remove and return an arbitrary set element.
            Raises KeyError if the set is empty.
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,4,5,6}
    print(number)
    number_pop = number.pop()
    print(number_pop)
    print(number)
    #运行结果
    {1, 2, 3, 4, 5, 6}
    1
    {2, 3, 4, 5, 6}
    View Code

    .clear()

    清空列表返回set()

        def clear(self, *args, **kwargs): # real signature unknown
            """ Remove all elements from this set. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,4,5,6}
    print(number)
    number.clear()
    print(number)
    #运行结果
    {1, 2, 3, 4, 5, 6}
    set()
    View Code

    .copy()

    复制集合

       def copy(self, *args, **kwargs): # real signature unknown
            """ Return a shallow copy of a set. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,4,5,6}
    print(number)
    number2 = number.copy()
    number.pop()
    print(number)
    print(number2)
    #运行结果
    {1, 2, 3, 4, 5, 6}
    {2, 3, 4, 5, 6}
    {1, 2, 3, 4, 5, 6}
    View Code

    .add()

    添加元素

        def add(self, *args, **kwargs): # real signature unknown
            """
            Add an element to a set.
            
            This has no effect if the element is already present.
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,4,5,6}
    print(number)
    number.add(7)
    print(number)
    #运行结果
    {1, 2, 3, 4, 5, 6}
    {1, 2, 3, 4, 5, 6, 7}
    View Code

    .difference()

    求差集,可以用“-”代替

        def difference(self, *args, **kwargs): # real signature unknown
            """
            Return the difference of two or more sets as a new set.
            
            (i.e. all elements that are in this set but not the others.)
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9}
    number1 = {2,3,8,9,11,12,10}
    print(number.difference(number1))
    print(number1.difference(number))
    print(number - number1)
    print(number1 - number)
    ##运行结果
    {1, 4, 5, 6}
    {10, 11, 12}
    {1, 4, 5, 6}
    {10, 11, 12}
    View Code

    .union()

    求并集,可用“|”代替

        def union(self, *args, **kwargs): # real signature unknown
            """
            Return the union of sets as a new set.
            
            (i.e. all elements that are in either set.)
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9}
    number1 = {2,3,8,9,11,12,10}
    print(number.union(number1))
    print(number | number1)
    #运行结果
    {1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12}
    {1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12}
    View Code

    difference_update.()

    差异更新,没有返回值,直接修改集合

        def difference_update(self, *args, **kwargs): # real signature unknown
            """ Remove all elements of another set from this set. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13}
    number1 = {2,3,8,9,11,12,10}
    number.difference_update(number1)
    print(number)
    #运行结果
    {1, 4, 5, 6, 13}
    View Code

    .discard()

     移除指定元素,如果集合内没有指定的元素,就什么都不做

        def discard(self, *args, **kwargs): # real signature unknown
            """
            Remove an element from a set if it is a member.
            
            If the element is not a member, do nothing.
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13}
    number.discard(1)
    print(number)
    #运行结果
    {2, 3, 4, 5, 6, 8, 9, 13}
    View Code

    .intersection()

    交集,可以用"&"代替

    def intersection(self, *args, **kwargs): # real signature unknown
            """
            Return the intersection of two sets as a new set.
            
            (i.e. all elements that are in both sets.)
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13}
    number1 = {1,2,3,4,5,13,16,17}
    print(number.intersection(number1))
    print(number & number1)
    #运行结果
    {1, 2, 3, 4, 5, 13}
    {1, 2, 3, 4, 5, 13}
    View Code

    .intersection_update()

    交集更新,没有返回值,直接修改集合

     def intersection_update(self, *args, **kwargs): # real signature unknown
            """ Update a set with the intersection of itself and another. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13}
    number1 = {1,2,3,4,5,13,16,17}
    number.intersection_update(number1)
    print(number)
    #运行结果
    {1, 2, 3, 4, 5, 13}
    View Code

    isdisjoint()

    当两个集合没有交集的时候,返回True,否则返回False

      def isdisjoint(self, *args, **kwargs): # real signature unknown
            """ Return True if two sets have a null intersection. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13}
    number1 = {16,17}
    print(number.isdisjoint(number1))
    #运行结果
    True
    number = {1,2,3,4,5,6,8,9,13,16}
    number1 = {16,17}
    #运行结果
    False
    View Code

    .issubset()

     当有2个集合A和B,A.issubset(B),A是否被B包含,如果是则返回True,否则返回False

      def issubset(self, *args, **kwargs): # real signature unknown
            """ Report whether another set contains this set. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13,16,17}
    number1 = {16,17}
    print(number1.issubset(number))
    #运行结果
    True
    View Code

    .issuperset()

    当有2个集合A和B,A.issuperset(B),A是否包含B,如果包含则返回True,否则返回False

     def issuperset(self, *args, **kwargs): # real signature unknown
            """ Report whether this set contains another set. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13,16,17}
    number1 = {16,17}
    print(number.issuperset(number1))
    #运行结果
    True
    View Code

    .symmetric_difference()

    取两个集合的差集,即取两个集合中对方都没有的元素

      def symmetric_difference(self, *args, **kwargs): # real signature unknown
            """
            Return the symmetric difference of two sets as a new set.
            
            (i.e. all elements that are in exactly one of the sets.)
            """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13,16,17}
    number1 = {16,17,18,19}
    print(number.symmetric_difference(number1))
    #运行结果
    {1, 2, 3, 4, 5, 6, 8, 9, 13, 18, 19}
    View Code

    .symmetric_difference_update()

    取两个集合的差集,即取两个集合中对方都没有的元素,并更新到集合中

       def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
            """ Update a set with the symmetric difference of itself and another. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13,16,17}
    number1 = {16,17,18,19}
    number.symmetric_difference_update(number1)
    print(number)
    #运行结果
    {1, 2, 3, 4, 5, 6, 8, 9, 13, 18, 19}
    View Code

    .update()

    取两个集合的并集,并更新到集合中

      def update(self, *args, **kwargs): # real signature unknown
            """ Update a set with the union of itself and others. """
            pass
    View Code

    举个例子

    number = {1,2,3,4,5,6,8,9,13,16,17}
    number1 = {16,17,18,19}
    number.update(number1)
    print(number)
    #运行结果
    {1, 2, 3, 4, 5, 6, 8, 9, 13, 16, 17, 18, 19}
    View Code

    七、字典

    在python里面,字典就是一系列的 键-值,每个值都与一个值是一一对应的,键可以是数字、字符串、列表和字典。实际上,可以将任何python对象用作字典的值。

    info = {
        'name':'Frank',
        'age':23,
        'hobbby':'reading',
        'address':'Shanghai',
    }
    print(info)
    print(info['age'])
    #运行结果
    {'name': 'Frank', 'age': 23, 'hobbby': 'reading', 'address': 'Shanghai'}
    23
    View Code

    方法如下:

    .keys()

    取出字典的键

       def keys(self): # real signature unknown; restored from __doc__
            """ D.keys() -> a set-like object providing a view on D's keys """
            pass
    View Code

    举个例子

    info = {
        'name':'Frank',
        'age':23,
        'hobbby':'reading',
        'address':'Shanghai',
    }
    print(info.keys())
    #运行结果
    dict_keys(['name', 'age', 'hobbby', 'address'])
    View Code

    .values()

    取出字典的值

      def values(self): # real signature unknown; restored from __doc__
            """ D.values() -> an object providing a view on D's values """
            pass
    View Code

    举个例子

    info = {
        'name':'Frank',
        'age':23,
        'hobbby':'reading',
        'address':'Shanghai',
    }
    #运行结果
    print(info.values())
    View Code

    .pop()

     弹出一个键值对,必须指定键

     举个例子

    info = {
        'name':'Frank',
        'age':23,
        'hobbby':'reading',
        'address':'Shanghai',
    }
    info.pop('name')
    print(info)
    #运行结果
    {'age': 23, 'hobbby': 'reading', 'address': 'Shanghai'}
    View Code

     .clear()

     清空字典里的键值对

     def clear(self): # real signature unknown; restored from __doc__
            """ D.clear() -> None.  Remove all items from D. """
            pass
    View Code

     举个例子

    info = {
        'name':'Frank',
        'age':23,
        'hobbby':'reading',
        'address':'Shanghai',
    }
    info.clear()
    print(info)
    #运行结果
    {}
    View Code

     .update()

     更新字典,如果有2个字典A和B,A.update(B),A和B相同的键的值会被B更新,而B中没有的键值对会被添加到A中

      def update(self, E=None, **F): # known special case of dict.update
            """
            D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
            If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
            If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
            In either case, this is followed by: for k in F:  D[k] = F[k]
            """
            pass
    View Code

     举个例子

    info = {
        'name':'Frank',
        'age':23,
        'hobby':'reading',
        'address':'Shanghai',
    }
    info_new = {
        'age':24,
        'hobby':'sleeping',
        'QQ':'110110',
    }
    info.update(info_new)
    print(info)
    #运行结果
    {'name': 'Frank', 'age': 24, 'hobby': 'sleeping', 'address': 'Shanghai', 'QQ': '110110'}
    View Code

     .copy()

     复制字典

    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
    }
    info_new = info.copy()
    info['name']='Jack'
    info['hobby'][0]='writing'
    print(info)
    print(info_new)
    #运行结果
    {'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}
    {'name': 'Frank', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}
    View Code

     我们会发现和列表中的copy一样,也存在字典里面的列表的元素被修改后,复制的字典也会自动修改,这个原因其实和前面的是一样的,我们这里也可以使用deep.copy

    import copy
    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
    }
    info_new = copy.deepcopy(info)
    info['name']='Jack'
    info['hobby'][0]='writing'
    print(info)
    print(info_new)
    #运行结果
    {'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai'}
    {'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'Shanghai'}
    View Code

     那字典里的字典会不会出现相同的问题呢?

    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
        'language':{1:'Python',2:'Go'},
    }
    info_new = info.copy()
    info['name']='Jack'
    info['hobby'][0]='writing'
    info['language'][2]='Java'
    print(info)
    print(info_new)
    #运行结果
    {'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}
    {'name': 'Frank', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}
    View Code

     答案是,是的,当我们想在修改原字典的时候,复制的字典保持不变,还是可以使用deep.copy来解决这个问题。

    import copy
    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
        'language':{1:'Python',2:'Go'},
    }
    info_new = copy.deepcopy(info)
    info['name']='Jack'
    info['hobby'][0]='writing'
    info['language'][2]='Java'
    print(info)
    print(info_new)
    #运行结果
    {'name': 'Jack', 'age': 23, 'hobby': ['writing', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Java'}}
    {'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'Shanghai', 'language': {1: 'Python', 2: 'Go'}}
    View Code

     这也是我们常说的深浅copy!

    .fromkeys()

     用来创建一个新的字典

       def fromkeys(*args, **kwargs): # real signature unknown
            """ Returns a new dict with keys from iterable and values equal to value. """
            pass
    View Code

     举个例子

    key = (1,2,3,4,5)
    value = 'Python'
    print(dict.fromkeys(key,value))
    #运行结果
    {1: 'Python', 2: 'Python', 3: 'Python', 4: 'Python', 5: 'Python'}
    View Code

     .get()

     根据键返回值,没有键则返回None

    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
    }
    print(info.get('hobby'))
    #运行结果
    ['reading', 'sleep']
    View Code

     .items()

     返回dict_items(),一般结合for循环使用

    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
    }
    print(info.items())
    #运行结果
    dict_items([('name', 'Frank'), ('age', 23), ('hobby', ['reading', 'sleep']), ('address', 'Shanghai')])
    View Code
    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
    }
    for k,v in info.items():
        print(k,"---",v)
    #运行结果
    name --- Frank
    age --- 23
    hobby --- ['reading', 'sleep']
    address --- Shanghai
    View Code

    .popitem()

     弹出最后一个键值,会返回一个元组,当弹空字典会报错

     def popitem(self): # real signature unknown; restored from __doc__
            """
            D.popitem() -> (k, v), remove and return some (key, value) pair as a
            2-tuple; but raise KeyError if D is empty.
            """
            pass
    View Code

     举个例子

    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
        'address':'Shanghai',
    }
    print(info.popitem())
    info.popitem()
    print(info)
    #举个例子
    ('address', 'Shanghai')
    {'name': 'Frank', 'age': 23}
    View Code

    .setdefault(key,value)

    如果键在字典中,则返回这个键的值,如果不在字典中,则向字典中插入这个键,并返回value,默认value位None
    举个例子

    info = {
        'name':'Frank',
        'age':23,
        'hobby':['reading','sleep'],
    }
    print(info.setdefault('name'))   #存在键name,返回值
    print(info)
    print(info.setdefault('address','shanghai'))  #不存在键address,返回'shanghai',添加键值对
    print(info)
    print(info.setdefault('QQ'))    #不存在键QQ,添加键QQ,返回None
    print(info)
    #运行结果
    Frank
    {'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep']}
    shanghai
    {'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'shanghai'}
    None
    {'name': 'Frank', 'age': 23, 'hobby': ['reading', 'sleep'], 'address': 'shanghai', 'QQ': None}
    View Code

    今天就写到这里了,欢迎各位大佬指出错误和不足之处,谢谢了!

  • 相关阅读:
    Android code wiki
    Android 屏蔽ScrollView滑动操作
    Android PorterDuff.Mode
    微信小程序开发——小程序分享转发
    支付宝小程序开发之与微信小程序不同的地方
    微信小程序快速移植支付宝小程序
    微信小程序开发——小程序API获取用户位置及异常流处理完整示例
    微信小程序开发——开发者工具中素材管理功能使用的注意事项
    js数组排序实用方法集锦
    chrome谷歌浏览器常用快捷键搜集整理
  • 原文地址:https://www.cnblogs.com/liubinsh/p/7049959.html
Copyright © 2020-2023  润新知