欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

总结Python数据类型及其方法

程序员文章站 2022-03-24 21:17:34
...

Python数据类型及其方法详解

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

一、整型和长整型

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

常用的method的如下:

.bit_length()

取最短bit位数

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子:

总结Python数据类型及其方法总结Python数据类型及其方法
number = 12  #1100 print(number.bit_length())#运行结果4
View Code

二、浮点型

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

总结Python数据类型及其方法总结Python数据类型及其方法
#浮点型number = 1.1print(type(number))#运行结果<class 'float'>
View Code

常用method的如下:

.as_integer_ratio()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
number = 0.25print(number.as_integer_ratio())#运行结果(1, 4)
View Code

.hex()

以十六进制表示浮点数

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
number = 3.1415print(number.hex())#运行结果0x1.921cac083126fp+1
View Code

.fromhex()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
print(float.fromhex('0x1.921cac083126fp+1'))#运行结果3.1415
View Code

.is_integer()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    def is_integer(self, *args, **kwargs): # real signature unknown""" Return True if the float is an integer. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
number = 3.1415number2 = 3.0print(number.is_integer())print(number2.is_integer())#运行结果False
True
View Code

三、字符类型

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

总结Python数据类型及其方法总结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()

字符串首字符大写

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = 'my name is Frank'#运行结果My name is frank
View Code

.center()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "Welcome Frank"print(flag.center(50,'*'))#运行结果******************Welcome Frank*******************
View Code

.count()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = 'aaababbcccaddadaddd'print(flag.count('a'))print(flag.count('a',0,3))#运行结果7
3
View Code

.encode()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = 'aaababbcccaddadaddd'print(flag.encode('utf8'))#运行结果b'aaababbcccaddadaddd'
View Code

.endswith()

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

总结Python数据类型及其方法总结Python数据类型及其方法
   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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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("\t")转换为空格

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "\thello python!"print(flag)print(flag.expandtabs())   #默认tabsize=8print(flag.expandtabs(20))#运行结果hello python!             #一个tab,长度为4个空格hello python!         #8个空格hello python!    #20个空格
View Code

.find()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "hello python!"print(flag.find('e'))print(flag.find('a'))print(flag.find('h',4,-1))#运行结果1
-1
9
View Code

.format()

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

总结Python数据类型及其方法总结Python数据类型及其方法
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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
#位置参数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()

格式化输出

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "hello python!"print(flag.index("e"))print(flag.index("o",6,-1))#运行结果1
10
View Code

.isalnum()

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

总结Python数据类型及其方法总结Python数据类型及其方法
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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "hellopython"flag1 = "hellopython22"print(flag.isalpha())print(flag1.isalpha())#运行结果True
False
View Code

.isdecimal()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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类似

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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中的标识符

总结Python数据类型及其方法总结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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "cisco"flag1 = "1cisco"flag2 = "print"print(flag.isidentifier())print(flag1.isidentifier())print(flag2.isidentifier())#运行结果True
False
True
View Code

.islower()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "cisco"flag1 = "cisco222"flag2 = "Cisco"print(flag.islower())print(flag1.islower())print(flag2.islower())#运行结果True
True
False
View Code

.isnumeric()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
   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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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
View Code

.isspace()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = '    '     #4个空格flag1 = '        '#2个tabprint(flag.isspace())print(flag1.isspace())#运行结果True
True
View Code

.istitle()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "Welcome Frank"flag1 = "Welcome frank"print(flag.istitle())print(flag1.istitle())#运行结果True
False
View Code

.isupper()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "WELCOME1"flag1 = "Welcome1"print(flag.isupper())print(flag1.isupper())#运行结果True
False
View Code

.join()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "welcome"print("#".join(flag))#运行结果w#e#l#c#o#m#e
View Code

.ljust()

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

总结Python数据类型及其方法总结Python数据类型及其方法
   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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "welcome"print(flag.ljust(20,"*"))#运行结果welcome*************
View Code

.rjust()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "welcome"print(flag.rjust(20,"*"))#运行结果*************welcome
View Code

.lower()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "WELcome"#运行结果welcome
View Code

.upper()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    def upper(self): # real signature unknown; restored from __doc__"""S.upper() -> str
        
        Return a copy of S converted to uppercase."""return ""
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "WELcome"print(flag.upper())#运行结果WELCOME
View Code

.title()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "welcome frank"print(flag.title())#运行结果Welcome Frank
View Code

.lstrip()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
   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
总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "welcome"print(flag.partition("e"))#运行结果('w', 'e', 'lcome')
View Code

.replace()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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,可根据索引范围查找

总结Python数据类型及其方法总结Python数据类型及其方法
   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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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类似,查找不到会报错

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "welcome frank ,e.."print(flag.rindex("e"))print(flag.rindex("e",0,3))#运行结果15
1
View Code

.rpartition()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
flag = "welcome frank ,e.."print(flag.rpartition("e"))print(flag.rpartition("x"))#运行结果('welcome frank ,', 'e', '..')
('', '', 'welcome frank ,e..')
View Code

.split()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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类似,只是它是从右向左分

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

字符串转换为列表

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
info = "hello,my name is Frank"print(info.splitlines())#运行结果['hello,my name is Frank']
View Code

.startswith()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

将字符串中的大小写互换

总结Python数据类型及其方法总结Python数据类型及其方法
   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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
info = "Hello,My name is Frank"print(info.swapcase())#运行结果hELLO,mY NAME IS fRANK
View Code

.zfill()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
info = "Hello,My name is Frank"print(info.zfill(50))#运行结果0000000000000000000000000000Hello,My name is Frank
View Code

四、列表

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

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Frank','Caroline','Bob','Saber']print(name.index("Frank"))print(name.index("Bob",1,-1))#运行结果02
View Code

.count()

计算某个元素的个数

总结Python数据类型及其方法总结Python数据类型及其方法
  def count(self, value): # real signature unknown; restored from __doc__""" L.count(value) -> integer -- return number of occurrences of value """return 0
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Frank','Caroline','Bob','Saber','Frank']print(name.count('Frank'))#运行结果2
View Code

.append()

在列表的最后添加元素

总结Python数据类型及其方法总结Python数据类型及其方法
    def append(self, p_object): # real signature unknown; restored from __doc__""" L.append(object) -> None -- append object to end """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Frank','Caroline','Bob','Saber','Frank']
name.append('Mei')print(name)#运行结果['Frank', 'Caroline', 'Bob', 'Saber', 'Frank', 'Mei']
View Code

.clear()

清空列表

总结Python数据类型及其方法总结Python数据类型及其方法
 def clear(self): # real signature unknown; restored from __doc__""" L.clear() -> None -- remove all items from L """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Frank','Caroline','Bob','Saber','Frank']
name.clear()print(name)#运行结果[]
View Code

.copy()

复制列表

总结Python数据类型及其方法总结Python数据类型及其方法
   def copy(self): # real signature unknown; restored from __doc__""" L.copy() -> list -- a shallow copy of L """return []
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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]会影响到我复制的列表的呢?
首先我们来看一下这个复制图解:

总结Python数据类型及其方法

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

总结Python数据类型及其方法

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

可以调用函数deepcopy().

总结Python数据类型及其方法总结Python数据类型及其方法
import copy
name = ['Saber','Frank',1,2,[3,4]]
name_cp=copy.deepcopy(name)
name[4][0]=5print(name)print(name_cp)#运行结果['Saber', 'Frank', 1, 2, [5, 4]]
['Saber', 'Frank', 1, 2, [3, 4]]
View Code

总结Python数据类型及其方法

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

.extend()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Saber','Frank']
nameto = ['Mei','Jack']
name.extend(nameto)print(name)#运行结果['Saber', 'Frank', 'Mei', 'Jack']
View Code

insert()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 def insert(self, index, p_object): # real signature unknown; restored from __doc__""" L.insert(index, object) -- insert object before index """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Saber','Frank']
name.insert(0,'Jack')print(name)#运行结果['Jack', 'Saber', 'Frank']
View Code

.pop()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

移除指定的元素

总结Python数据类型及其方法总结Python数据类型及其方法
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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Saber','Frank','Caroline','Jack']
name.remove('Frank')print(name)#运行结果['Saber', 'Caroline', 'Jack']
View Code

.reverse()

列表反转,永久修改

总结Python数据类型及其方法总结Python数据类型及其方法
    def reverse(self): # real signature unknown; restored from __doc__""" L.reverse() -- reverse *IN PLACE* """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
name = ['Saber','Frank','Caroline','Jack']
name.reverse()print(name)#运行结果['Jack', 'Caroline', 'Frank', 'Saber']
View Code

.sort()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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

总结Python数据类型及其方法总结Python数据类型及其方法
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()

计算指定元素的个数

总结Python数据类型及其方法总结Python数据类型及其方法
   def count(self, value): # real signature unknown; restored from __doc__""" T.count(value) -> integer -- return number of occurrences of value """return 0
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
number = (1,2,2,2,1)print(number.count(2))#运行结果3
View Code

.index()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
number = (1,2,2,2,1)print(number.index(2))print(number.index(2,2,-1))#运行结果1
2
View Code

六、集合

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

总结Python数据类型及其方法总结Python数据类型及其方法
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()

移除指定的元素

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

总结Python数据类型及其方法总结Python数据类型及其方法
    def clear(self, *args, **kwargs): # real signature unknown""" Remove all elements from this set. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
number = {1,2,3,4,4,5,6}print(number)
number.clear()print(number)#运行结果{1, 2, 3, 4, 5, 6}
set()
View Code

.copy()

复制集合

总结Python数据类型及其方法总结Python数据类型及其方法
   def copy(self, *args, **kwargs): # real signature unknown""" Return a shallow copy of a set. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

添加元素

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

求并集,可用“|”代替

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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.()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    def difference_update(self, *args, **kwargs): # real signature unknown""" Remove all elements of another set from this set. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
    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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

交集,可以用"&"代替

总结Python数据类型及其方法总结Python数据类型及其方法
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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 def intersection_update(self, *args, **kwargs): # real signature unknown""" Update a set with the intersection of itself and another. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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

总结Python数据类型及其方法总结Python数据类型及其方法
  def isdisjoint(self, *args, **kwargs): # real signature unknown""" Return True if two sets have a null intersection. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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

总结Python数据类型及其方法总结Python数据类型及其方法
  def issubset(self, *args, **kwargs): # real signature unknown""" Report whether another set contains this set. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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

总结Python数据类型及其方法总结Python数据类型及其方法
 def issuperset(self, *args, **kwargs): # real signature unknown""" Report whether this set contains another set. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
number = {1,2,3,4,5,6,8,9,13,16,17}
number1 = {16,17}print(number.issuperset(number1))#运行结果True
View Code

.symmetric_difference()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
   def symmetric_difference_update(self, *args, **kwargs): # real signature unknown""" Update a set with the symmetric difference of itself and another. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

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

总结Python数据类型及其方法总结Python数据类型及其方法
  def update(self, *args, **kwargs): # real signature unknown""" Update a set with the union of itself and others. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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对象用作字典的值。

总结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()

取出字典的键

总结Python数据类型及其方法总结Python数据类型及其方法
   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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
info = {'name':'Frank','age':23,'hobbby':'reading','address':'Shanghai',
}print(info.keys())#运行结果dict_keys(['name', 'age', 'hobbby', 'address'])
View Code

.values()

取出字典的值

总结Python数据类型及其方法总结Python数据类型及其方法
  def values(self): # real signature unknown; restored from __doc__""" D.values() -> an object providing a view on D's values """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
info = {'name':'Frank','age':23,'hobbby':'reading','address':'Shanghai',
}#运行结果print(info.values())
View Code

.pop()

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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
info = {'name':'Frank','age':23,'hobbby':'reading','address':'Shanghai',
}
info.pop('name')print(info)#运行结果{'age': 23, 'hobbby': 'reading', 'address': 'Shanghai'}
View Code

.clear()

清空字典里的键值对

总结Python数据类型及其方法总结Python数据类型及其方法
 def clear(self): # real signature unknown; restored from __doc__""" D.clear() -> None.  Remove all items from D. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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中

总结Python数据类型及其方法总结Python数据类型及其方法
  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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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()

复制字典

总结Python数据类型及其方法总结Python数据类型及其方法
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

总结Python数据类型及其方法总结Python数据类型及其方法
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

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

总结Python数据类型及其方法总结Python数据类型及其方法
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来解决这个问题。

总结Python数据类型及其方法总结Python数据类型及其方法
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()

用来创建一个新的字典

总结Python数据类型及其方法总结Python数据类型及其方法
   def fromkeys(*args, **kwargs): # real signature unknown""" Returns a new dict with keys from iterable and values equal to value. """pass
View Code

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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

总结Python数据类型及其方法总结Python数据类型及其方法
info = {'name':'Frank','age':23,'hobby':['reading','sleep'],'address':'Shanghai',
}print(info.get('hobby'))#运行结果['reading', 'sleep']
View Code

.items()

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

总结Python数据类型及其方法总结Python数据类型及其方法
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
总结Python数据类型及其方法总结Python数据类型及其方法
info = {'name':'Frank','age':23,'hobby':['reading','sleep'],'address':'Shanghai',
}for k,v in info.items():print(k,"---",v)#运行结果name --- Frank
age --- 23hobby --- ['reading', 'sleep']
address --- Shanghai
View Code

.popitem()

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

总结Python数据类型及其方法总结Python数据类型及其方法
 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

举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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
举个例子

总结Python数据类型及其方法总结Python数据类型及其方法
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,返回Noneprint(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

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

以上就是总结Python数据类型及其方法的详细内容,更多请关注其它相关文章!