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‘>

常用的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

举个例子:

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

二、浮点型

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

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

常用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

举个例子

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

.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 ""

举个例子

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

.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
        """

举个例子

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

.is_integer()

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

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

举个例子

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

三、字符类型

字符串就是一些列的字符,在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  

常用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 ""

举个例子

name = ‘my name is Frank‘
#运行结果
My name is frank

.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 ""

举个例子

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

.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

举个例子

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

.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""

举个例子

flag = ‘aaababbcccaddadaddd‘
print(flag.encode(‘utf8‘))
#运行结果
b‘aaababbcccaddadaddd‘

.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

举个例子

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

.expandtabs()

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

  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 ""

举个例子

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

.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

举个例子

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

.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

举个例子

#位置参数
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

.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 ""

举个例子

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 !

.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

举个例子

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

.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

举个例子

flag = "hellopython"
flag1 = "hellopython22"
flag2 = "hellopython!!"
flag3 = "[email protected]#!#@[email protected]"
print(flag.isalnum())
print(flag1.isalnum())
print(flag2.isalnum())
print(flag3.isalnum())
#运行结果
True
True
False
False

.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

举个例子

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

.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

举个例子

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

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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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 ""

举个例子

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

.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 ""

举个例子

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

.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 ""

举个例子

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

.lower()

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

    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""

举个例子

flag = "WELcome"
#运行结果
welcome

.upper()

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

    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""

举个例子

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

.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 ""

举个例子

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

.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 ""

举个例子

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

.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 ""

举个例子

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

.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 ""

举个例子

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

.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

  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 ""

举个例子

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

.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

举个例子

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

.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 ""

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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 []

举个例子

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..‘]

.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 []

举个例子

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

.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 []

举个例子

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

.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

举个例子

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

.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 ""

举个例子

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

.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 ""

举个例子

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

四、列表

列表是由一系列按特定顺序排列的元素组成。在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”个开始打印

常见方法如下:

.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

举个例子

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

.count()

计算某个元素的个数

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

举个例子

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

.append()

在列表的最后添加元素

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

举个例子

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

.clear()

清空列表

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

举个例子

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

.copy()

复制列表

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

举个例子

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]]

我们会发现,我们给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]]

这样会给复制后的列表中的列表重新开辟一个地址空间,然后指向列表中列表的元素的地址空间,这样你怎么改变原列表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

举个例子

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

insert()

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

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

举个例子

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

.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

举个例子

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‘]

.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

举个例子

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

.reverse()

列表反转,永久修改

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

举个例子

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

.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

举个例子

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]

五、元组

元组和列表类似,不同的是元组的元素是不能修改的,使用小括号"()"括起来,用逗号","分开,其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)

常见方法如下:

.count()

计算指定元素的个数

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

举个例子

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

.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

举个例子

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

六、集合

集合是一系列无序的元素组成,所有你不能使用索引值,在打印的时候,元组是自然排序,天然去重的,其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}

常用方法如下

.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

举个例子

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}

.pop()

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

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

举个例子

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}

.clear()

清空列表返回set()

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

举个例子

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

.copy()

复制集合

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

举个例子

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}

.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

举个例子

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}

.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

举个例子

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}

.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

举个例子

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}

difference_update.()

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

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

举个例子

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}

.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

举个例子

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

.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

举个例子

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}

.intersection_update()

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

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

举个例子

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}

isdisjoint()

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

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

举个例子

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

.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

举个例子

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

.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

举个例子

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

.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

举个例子

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}

.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

举个例子

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}

.update()

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

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

举个例子

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}

七、字典

在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

方法如下:

.keys()

取出字典的键

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

举个例子

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

.values()

取出字典的值

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

举个例子

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

.pop()

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

举个例子

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

.clear()

清空字典里的键值对

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

举个例子

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

.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

举个例子

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‘}

.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‘}

我们会发现和列表中的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‘}

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

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‘}}

答案是,是的,当我们想在修改原字典的时候,复制的字典保持不变,还是可以使用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‘}}

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

.fromkeys()

用来创建一个新的字典

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

举个例子

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

.get()

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

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

.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‘)])

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

.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

举个例子

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

.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}

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

时间: 2024-11-25 07:42:21

Python数据类型及其方法详解的相关文章

Python List insert()方法详解

1.功能insert()函数用于将指定对象插入列表的指定位置. 2.语法list.insert(index, obj) 3.参数index: 对象obj需要插入的索引位置.obj: 插入列表中的对象. 共有如下5种场景:场景1:index=0时,从头部插入obj场景2:index > 0 且 index < len(list)时,在index的位置插入obj场景3:当index < 0 且 abs(index) < len(list)时,从中间插入obj,如: -1 表示从倒数第1

Python 字符串方法详解

Python 字符串方法详解 本文最初发表于赖勇浩(恋花蝶)的博客(http://blog.csdn.net/lanphaday),如蒙转载,敬请保留全文完整,切勿去除本声明和作者信息. 在编程中,几乎90% 以上的代码都是关于整数或字符串操作,所以与整数一样,Python 的字符串实现也使用了许多拿优化技术,使得字符串的性能达到极致.与 C++ 标准库(STL)中的 std::string 不同,python 字符串集合了许多字符串相关的算法,以方法成员的方式提供接口,使用起来非常方便. 字符

49.Python使用requests包进行HTTP交互方法详解

简介 使用方法 传递QUERY参数 定制请求头 填写cookie 填充请求体 处理响应对象 重定向与访问历史 超时 Session对象 根据响应获取请求 SSL认证 HTTP认证 基本认证 摘要认证 代理场景 HTTPHTTPS代理 SOCKS代理 简介 Python的HTTP包有urllib.urllib2.httplib等,但是都需要了解较多的HTTP原理才能编码,借助requests包可以在较高的抽象层次上完成HTTP交互过程的开发.安装requests使用pip install requ

Python:file/file-like对象方法详解【单个文件读写】

IO中读写文件操作方法汇总!----The_Third_Wave的学习笔记! 本文由@The_Third_Wave(Blog地址:http://blog.csdn.net/zhanh1218)原创.不定期更新,有错误请指正. Sina微博关注:@The_Third_Wave 如果这篇博文对您有帮助,为了好的网络环境,不建议转载,建议收藏!如果您一定要转载,请带上后缀和本文地址. class file(object) |  file(name[, mode[, buffering]]) -> fi

Python中格式化format()方法详解

Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任何东西都是对象; 字符串的参数使用{NUM}进行表示,0, 表示第一个参数,1, 表示第二个参数, 以后顺次递加; 使用":", 指定代表元素需要的操作, 如":.3"小数点三位, ":8"占8个字符空间等; 还可以添加特定的字母, 如: 'b' - 二进制. 将数字以2为基数

Python中time模块详解

在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. 在开始之前,首先要说明这几点: 在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素.由于Python的time模块实现主要调用C库,所以各个平台可能有所不同. UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间.在中国为UTC+8.DST

JavaScript原生对象属性和方法详解——Array对象 转载

length 设置或返回 数组中元素的数目. 注意:设置 length 属性可改变数组的大小.如果设置的值比其当前值小,数组将被截断,其尾部的元素将丢失.如果设置的值比它的当前值大,数组将增大,新的元素被添加到数组的尾部,它们的值为 undefined.所以length不一定代表数组的元素个数. var arr = new Array(3) arr[0] = "John" arr[1] = "Andy" arr[2] = "Wendy" cons

Python对Excel操作详解

  Python对Excel操作详解 文档摘要: 本文档主要介绍如何通过python对office excel进行读写操作,使用了xlrd.xlwt和xlutils模块.另外还演示了如何通过Tcl  tcom包对excel操作. 关键字: Python.Excel.xlrd.xlwt.xlutils.TCl.tcom     1 Python简介 Python是一种面向对象.直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定.它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务.

python中threading模块详解(一)

python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thread模块更高层的API来提供线程的并发性.这些线程并发运行并共享内存. 下面来看threading模块的具体用法: 一.Thread的使用 目标函数可以实例化一个Thread对象,每个Thread对象代表着一个线程,可以通过start()方法,开始运行. 这里对使用多线程并发,和不适用多线程并发做