python数据类型及操作方法

python内建数据类型:

数据类型示例创建空数据类型类型转换
int 整型-int(1.4) >>1
float 浮点型1.0-float(1) >>1.0
str 字符型‘school’-str(1) >>‘1’
bool 布尔型True/False-bool(1) >>True
tuple 元组(1,2,3,4)()tuple([1,2,3]) >>(1,2,3)
list 列表[1,2,3,4][]list((1,2,3)) >>[1,2,3]
dict 字典{‘name’:‘wwl’,‘age’:24}{}-
set 集合{1,2,3,4}set()set((1,1,2,3)) >>{1,2,3}

注意点:

  1. 在python中,{}为创建空字典,如果创建空集合,应使用set()。
  2. 类型转换:一般为int,float.str之间进行相互转换,元组,列表,集合之间进行相互转换。
  3. int(‘1.4’) >>>ValueError
    当int对字符串进行类型转换时,如果字符串不是由纯数字组成,会报错。
  4. bool(1) >>> True
    布尔类型转化时,整数零,空字符串,None,空元组,空列表,空字典会被转化为False,其余均被转化为True。
  5. 列表和元组,如果转换为集合类型,一般情况下,是为了去重,利用集合中不能存在重复元素的特性。

python数据类型判断:

  1. type() :判断并返回数据的类型

    		type(4)               >>>    <class 'int'> 
    		type(1.0)             >>>    <class 'float'>
    		type('school')        >>>    <class 'str'>
    		type(True)            >>>    <class 'bool'>
    		type((1,2,3,4))       >>>    <class 'tuple'>
    		type([1,2,3,4])       >>>    <class 'list'>
    		type({1,2,3,4})       >>>    <class 'set'>
    		type({"name":"wwl","age":24}) >>>    <class 'dict'>
    
  2. isinstance(对象,类):判断对象是否是所写的数据类型,返回True或False

    		isinstance(4,int)                >>>  True 
    		isinstance(1.0,float)            >>>  True 
    		isinstance('school',str)         >>>  True 
    		isinstance(True,bool)            >>>  True 
    		isinstance((1,2,3,4),tuple)      >>>  True 
    		isinstance([1,2,3,4],list)       >>>  True 
    		isinstance({1,2,3,4},set)        >>>  True 
    		isinstance({"name":"wwl","age":24},dict)    >>>  True 
    
  3. issubclass(A,B):判断A类是否是B类的子类,返回True或False

    #创建两个类:A类和B类,其中B类是父类,A类是子类,继承于B类
    class B(object):
    	def __init__(self,name):
    		self.name = name 
    		
    class A(B):
    	def __init__(self,name,age):
    	    super(B,self).__init__(name)
    	    self.age = age
    	
    print(issubclass(A,B))   >>>  True 
    

注意点:

  1. type()与isinstance()都是用于判断对象的数据类型(判断对象是由哪个类实例化生成的);区别在于isinstance()在进行判断时会认为子类是父类的一部分,对象属于其子类亦属于其父类。

    class B(object):
    	def __init__(self,name):
    		self.name = name 
    		
    class A(B):
    	def __init__(self,name,age):
    	    super(B,self).__init__(name)
    	    self.age = age
    
    student = A('wwl',24)
    #student是由A类实例化的对象,在进行isinstance()判断时,会发现student既属于A类也属于其父类B
    print(isinstance(student,A))    >>>  True 
    print(isinstance(student,B))    >>>  True 
    

python数据类型的常用操作方法:

  1. int:整型 ,float:浮点型
    一般是数学运算,常用运算符:+,-,*,/,//,%,**

  2. 字符串的常用操作方法:

    方法示例作用返回值类型
    lower()‘SCHOOL’.lower() >>> ‘school’小写字符串
    upper()‘school’.upper() >>> ‘SCHOOL’大写字符串
    split(str,num)‘fsgst’.split(‘s’) >>> [‘f’, ‘g’, ‘t’]分割字符串列表
    center(width,fillchar)‘name’.center(10,’-’) >>> ‘—name—’居中填充字符串
    replace(old,new)‘school’.replace(‘o’,‘e’) >>> 'scheel ’替换字符串
    strip()’ school '.strip() >>> ‘school’去除左右两侧的空格字符串
    join(seq)‘a’.join(‘pid’) >>> ‘paiad’连接序列中的元素字符串
    index()‘school’.index(‘c’) >>> 1索引数字
    find()‘school’.find(‘c’) >>> 1索引数字
    count()‘school’.count(‘o’) >>> 2字符在字符串中出现的次数数字
    capitalize()‘study WELL’.capitalize() >>> ‘Study well’首字母大写,其余小写字符串
    title()‘study well’.title() >>> ‘Study Well’所有单词首字母大写,其余小写字符串
    swapcase()‘schOOl’.swapcase() >>> ‘SCHooL’大写变小写,小写变大写字符串
    zfill(width)‘school’.zfill(8) >>> ‘00school’右对齐,前面补0字符串
    encode(‘UTF-8’)‘生活’.encode(‘UTF-8’) >>> b’\xe7\x94\x9f\xe6\xb4\xbb’编码字符串字节
    decode(‘UTF-8’)b’\xe7\x94\x9f\xe6\xb4\xbb’.decode(‘UTF-8’) >>> ‘生活’解码字符串

    注意点:
    1.split()返回的是一个列表;
    2.join(seq)的参数是一个序列,返回的是一个新字符串;
    3.find()与index()都是用于查找字符在字符串中的索引,不同点是:当字符不存在时, find()方法返回-1,而index()会报ValueError错误;

    a = 'sssdfeadf'
    a.find('h')
    -1
    a.index('h')
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    ValueError: substring not found
    

    4.编码:encode()与decode()
    常用编码格式有两种:UTF-8和GBK;他们都是将字符串编码为字节类型,不同点是在UTF-8编码中,一个汉字对应是3个字节,而GBK是对应两个字节

    a = '生活'
    a.encode('UTF-8')
    b'\xe7\x94\x9f\xe6\xb4\xbb'    #在UTF-8编码规则中,两个个汉字被编码为6个字节
    a.encode('GBK')
    b'\xc9\xfa\xbb\xee'            #在GBK编码规则中,两个汉字被编码为4个字节
    
    a.encode('UTF-8').decode('GBK')    
    '鐢熸椿'                            
    #文字乱码的由来:"生活"两个汉字用UTF-8编码后,变为6个字节,当用GBK解码时,会把6个字节解码为3个汉字(因为GBK编码中2个字节对应一个汉字),所以最后变为了'鐢熸椿'3个汉字
    

    5.判断字符串中字符出现的次数:

    a = 'asdfasfafafasd'
    #可以使用count()方法查看某个字符在字符串中出现的次数
    a.count('s') >>>3
    #还可以使用collections模块的Counter方法查看每个字符出现的次数
    from  collections import Counter
    Counter(a) >>> Counter({'a': 5, 'f': 4, 's': 3, 'd': 2})
    #如何在Counter({'a': 5, 'f': 4, 's': 3, 'd': 2})中把单个字符的次数取出,与字典中取值一样,dict['key'] >>> value
    
  3. bool类型:True/False
    布尔类型转化:0,‘’,(),[],{},None转化为False;其余均转化为True
    any(iterable)与all(iterable)方法:参数为可迭代对象,返回True或False
    any(iterable):遍历,将iterable中的所有元素均转化为bool类型,只要有一个为True,就返回True;
    all(iterable):遍历,将iterable中的所有元素均转化为bool类型,都是True才返回True,否则返回False;

    any((0,None))   >>> False
    any((0,None,1))   >>> True     #any()类似于or,有一个为True,就返回True
    all((0,1,2,3))    >>> False
    all((1,2,3))    >>> True       #all()类似于and,都是True,才返回True
    
  4. 列表的常用操作方法:

    增加元素:append(obj)、insert(index.obj)、extend(seq)
    list1 = [1,2,3]
    #append() 方法用于在列表末尾添加新的对象。该方法无返回值,但是会修改原来的列表。
    list1.append(4)
    print(list1)  >>>  [1, 2, 3, 4]
    #insert() 函数用于将指定对象插入列表的指定位置。该方法没有返回值,但会在列表指定位置插入对象。
    list1.insert(1,6)
    print(list1)  >>>  [1, 6, 2, 3, 4]
    #extend(seq) 遍历括号中序列中的每个元素,依次追加到列表末尾处
    list1.extend('asd')
    print(list1)  >>>  [1, 6, 2, 3, 4,'a','s','d']
    
    删除元素:pop()、remove()、clear()
    list1 = [1, 6, 2, 3, 4, 's', 's', 'd']
    #pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
    list1.pop()  >>>  'd' 
    list1.pop(1)  >>>  6
    print(list1)  >>>  [1, 2, 3, 4, 's', 's']
    #remove() 该方法没有返回值但是会移除列表中的某个值的第一个匹配项。
    list1.remove(2)
    print(list) >>>  [1, 3, 4, 's', 's']
    #clear() 函数用于清空列表,类似于 del a[:]
    list1.clear()    >>>  []
    
    其余方法:index()、copy()、sort(key=func,reverse=True)、reverse()、count()
    list1 = [1,3,3]
    #ndex() 函数用于从列表中找出某个值第一个匹配项的索引位置。
    list1.index(1)   >>>  0
    #copy() 函数用于复制列表,类似于 a[:],返回复制后的新列表。
    list1.copy()  >>>  [1, 3, 2]
    #sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
    list2 = list1.sort() 
    print(list2)    >>>  [1, 2, 3]
    #reverse() 函数用于反向列表中元素,类似于a[::-1]
    list2.reverse()  
    print(list2)  >>>   [3, 2, 1]
    #count() 方法用于统计某个元素在列表中出现的次数;也可用collections模块的Counter方法
    list2.count(1)  >>>  1
    
    from collections import Counter
    Counter(list2)  >>>  Counter({3: 1, 2: 1, 1: 1})
    

    注意点:
    1.pop()与remove() :pop()与remove()均为移除列表中的元素,不同之处在于pop()会返回移除的元素,而remove()没有返回值,除此之外,pop()与remove()在一些特定情况下,会发生错误。

    #1.当多空列表使用pop()方法时,会报IndexError错误
    list = []
    list.pop()
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    IndexError: pop from empty list
    #2.当使用remove()方法是,如果移除元素不在列表内,会报ValueError错误
    list =[1,2]
    list.remove(3)
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    ValueError: list.remove(x): x not in list
    

    2.index():如果查询元素不在列表内,会报ValueError错误

    list = [1,2,3]
    list.index(4)
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    ValueError: 4 is not in list
    

    3.copy():为浅拷贝

    list1=[1,2,3,[4,5]]
    list2 = list1.copy()
    print(list2)
    [1, 2, 3, [4, 5]]
    #可以看到list1与list2的父级元素的地址是不同的,说明list1与list2是两个不同的对象
    id(list1)   >>>  75999784       
    id(list2)   >>>  76003784
    #再看list1与list2的子级元素的地址是一样的,说明list1与list2的子级元素指向同一个对象。
    id(list1[3])  >>>   75999880
    id(list2[3])  >>>   75999880
    #其中一个对象子级元素的更改会影响另一个子级元素的更改,我们确认一下
    list1[3][1]=8
    print(list1)   >>>  [1, 2, 3, [4, 8]]
    print(list2)   >>>  [1, 2, 3, [4, 8]]
    

    4.sort(key=func,reverse=True)与sorted(list,key=func,reverse=True):都是对列表进行排序,不同点在于sort()是在原列表的基础上排序,而sorted()是生成另外一个新的列表。

    list1 = [[2,1],[5,3],[4,2],[3,4]]
    def  px(ele):
         return ele[0]
    list1.sort(key=px)
    print(list1)   >>>  [[2, 1], [3, 4], [4, 2], [5, 3]]
    sorted(list1,key=lambda ele:ele[1])  >>>   [[2, 1], [4, 2], [5, 3], [3, 4]]
    #其中key指定的函数为排序的规则,当进行sort()或者sorted()操作时,这两种方法会遍历列表中的元素,并将其作为参数传递给key所指定的函数,然后根据返回结果对比排序
    
  5. 元组(tuple):元组是不可变的,其不可变是指元组所指向的内存中的内容不可变。

    a =(1,2,3)
    a[0]=4
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
    id(a)  >>>  73448328
    a = (4,2,3)
    id(a)  >>>  75813832
    #从id可以看出,更改前后不是同一个对象,更改后只是生成了一个新对象,原对象没有改变。
    
  6. 字典的常用操作方法:

    更新字典:dict.update(dict2)
    #dict.update(dict2)把字典参数 dict2 的 key/value(键/值) 对更新到字典 dict 里。
    dict1 = {'name':'wwl','age':24}
    dict2 = {'sex':'男'}
    dict1.update(dict2)
    print(dict1)   >>>   {'name': 'wwl', 'age': 24, 'sex': '男'}
    
    取值:dict[key]、dict.get(key,default)、dict.setdefault(key,default)
    dict1 = {'name':'wwl','age':24}
    #当使用dict[key]取字典里的值时,如果key存在,则返回key所对应的value,若不存在,则报KeyError错误
    dict1['name']   >>>   'wwl'
    dict1['sex']
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    KeyError: 'sex'
    #当使用dict.get(key,default)取值时,如果key存在,则返回Key所对应的value,若不存在,则返回default值
    dict1.get('sex','y')   >>>   'y'
    #当使用dict.setdefault(key,default)取值时,如果key存在,则返回key对应的value,如果不存在,就插入 key 及设置的默认值 default,并返回 default ,default 默认值为 None
    dict1.setdefault('sex','男')   >>>   '男'
    print(dict1)   >>>   {'name': 'wwl', 'age': 24, 'sex': '男'}
    
    删除元素:dict.pop()、dict.popitem()、dict.clear()
    dict1 = {'name': 'wwl', 'age': 24, 'sex': '男'}
    #pop(key[,default])删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
    dict1.pop('age')   >>>  24
    #Python 字典 popitem() 方法随机返回并删除字典中的最后一对键和值(元组形式)。如果字典已经为空,却调用了此方法,就报出KeyError异常。
    dict1.popitem()  >>>  ('sex', '男') 
    dict2 = {}
    dict2.popitem()
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    KeyError: 'popitem(): dictionary is empty'
    # clear() 函数用于删除字典内所有元素。
    dict3 = {'name':'xi','age':22}
    dict3.clear()
    print(dict3)
    {}
    
    其余方法:dict.values()、dict.keys()、dict.items()、dict.fromkeys()、dict.copy()
    dict1 = {'name':'wwl','age':24,'sex':'男'}
    #dict.values()、dict.keys()、dict.items()返回数据均为迭代器类型
    dict1.keys()   >>>   dict_keys(['name', 'age', 'sex'])
    dict1.values()    >>>   dict_values(['wwl', 24, '男'])
    dict1.items()    >>>   dict_items([('name', 'wwl'), ('age', 24), ('sex', '男')])
    #dict.fromkeys(seq,value) 函数用于创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值,默认为none
    list1 = ['name','age','sex']
    dict2.fromkeys(list1)  >>> {'name': None, 'age': None, 'sex': None}
    #copy() 函数返回一个字典的浅复制,与list.copy()同理
    dict1 = {'name':'wwl'}
    dict2 = dict1.copy()
    print(dict2)    >>>   {'name': 'wwl'}
    
  7. 集合的常用操作方法:

    添加元素:add()、update()
    #add() 方法用于给集合添加元素,如果添加的元素在集合中已存在,则不执行任何操作。
    a = {1,2,3}
    a.add(4)
    print(a)  >>>   {1, 2, 3, 4}
    #update() 方法用于修改当前集合,参数必须是可迭代对象,遍历对象依次添加到当前集合中,如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略。
    b = {1,2,3}
    b.update('sad')
    print(b)  >>>  {1, 2, 3, 's', 'd', 'a'}
    b.update({4,5})
    print(b)  >>>   {1, 2, 3, 's', 4, 5, 'd', 'a'}
    b.update([6,7])   
    print(b)  >>>   {1, 2, 3, 's', 4, 5, 6, 7, 'd', 'a'}
    b.update((8,9))
    print(b)  >>>    {1, 2, 3, 's', 4, 5, 6, 7, 8, 9, 'd', 'a'}
    b.update({'name':'wwl','age':24})    #如果对象是字典,只会添加key到集合中
    print(b)  >>>  {1, 2, 3, 's', 4, 5, 6, 7, 8, 9, 'age', 'd', 'name', 'a'}
    
    移除元素:pop()、remove()、discard()、clear()
    a = {5,2,3,4,1,6}
    #pop() 方法用于随机移除一个元素。如果集合为空,会报KeyError错误
    a.pop()  >>>  1
    a.pop()  >>>  2
    #remove() 方法用于移除集合中的指定元素。不同于 discard() 方法,因为 remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。
    a.remove(3)
    print(a)  >>>   {4, 5, 6}
    a.remove(7)
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    KeyError: 7
    #discard() 方法用于移除指定的集合元素。无论移除元素存不存在,都不会报错
    a.discard(4)
    print(a) >>>  {5, 6}
    a.discard(7)   #没有报错
    print(a) >>>  {5, 6}
    #clear() 方法用于移除集合中的所有元素。
    a.clear()
    print(a)  >>>  set()
    
    集合之间常用的几种运算:- ,&, |, ^
    a = {1,2,3,4,5}
    b ={4,5,6,7,8,9}
    #集合是可以做减法运算的
    print(a - b)   >>>  {1, 2, 3}    #在a集合中,却不在b集合
    print(b - a)   >>>  {8, 9, 6, 7}  #在b集合中,却不在a集合
    #集合之间进行&运算,求交集
    print(a & b)   >>>  {4, 5}
    #集合之间进行|运算,求并集
    print(a | b)   >>>  {1, 2, 3, 4, 5, 6, 7, 8, 9}
    #集合之间进行^运算,求两个集合中不重复的元素集合。
    print(a ^ b)   >>>  {1, 2, 3, 6, 7, 8, 9}
    

版权声明:本文为weixin_50875614原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。