zoukankan      html  css  js  c++  java
  • 数据类型

    一.数字类型

    整型int
    ======================================基本使用======================================
    1、用途:记录年龄、等级、号码等

    2、定义方式
    age=10 # age=int(10)

    类型转换
    print(int(3.1))
    res=int('1111111')
    print(res,type(res))


    res=float('111111.1')
    print(res,type(res))

    了解(**)
    十进制转成。。。进制
    print(bin(13))
    print(oct(13))
    print(hex(13))


    3、常用操作+内置的方法

    ======================================该类型总结====================================
    存一个值

    不可变
    x=10
    print(id(x))
    x=11
    print(id(x))

    浮点型fioat

    ======================================基本使用======================================
    1、用途:记录身高、体重、薪资等

    2、定义方式
    salary=10.1 # salary=float(10.1)

    类型转换
    print(float(10))
    print(float(1.1))
    print(float('1.1'))

    3、常用操作+内置的方法

    ======================================该类型总结====================================
    存一个值

    不可变
    x=10.3
    print(id(x))
    x=11.2
    print(id(x))

    二.字符串类型

    字符串类型str

    ======================================基本使用======================================
    1、用途:记录描述性值的状态,比如名字、性别等

    2、定义方式
    msg='hello world' #msg=str('hello world')

    类型转换: 可以把任意类型专场字符串类型
    res1=str(10)
    res2=str(10.3)
    res3=str([1,2,3])
    res4=str({'x':1}) # res4="{'x':1}"

    print(type(res1))
    print(type(res2))
    print(type(res3))
    print(type(res4)) #<class 'str'>

    3、常用操作+内置的方法
    优先掌握的操作:(*****)
    1、按索引取值(正向取+反向取) :只能取
    msg='hello world'
    print(type(msg[0])) #<class 'str'>
    print(msg[-1]) #d

    2、切片(顾头不顾尾,步长)
    msg='hello world'
    print(msg[0]+msg[1]+msg[2]) #hel
    print(msg[0:5]) #hello
    print(msg[0:5:2]) #hlo
    print(msg[0:]) #hello word
    print(msg[:]) #hello word
    print(msg[-1:-5:-1]) #dlro
    print(msg[::-1]) #dlrow olleh

    3、长度len:统计的是字符的个数
    msg=‘xxx’
    print(len(msg)) #3

    4、成员运算in和not in:判断一个子字符串是否存在与一个大字符串中
    msg='hello world'
    print('h' in msg) #True
    print('ho' not in msg) #True

    5、移除空白strip:移除字符串左右两边的某些字符
    msg='     hello     '

    print(msg)   #       hello
    print(msg.strip(' ')) #hello
    print(msg.strip()) #hello

    6、切分split: 把有规律的字符串切成列表从而方便取值
    info='egon:18:180:150'
    res=info.split(':')
    print(res) #['egon','18','180','150']
    print(res[1]) #18
    值的拼凑
    s1=res[0]+':'+res[1]+':'+res[2]+':'+res[3]
    s1=''
    for item in res:
      s1+=item
    print(s1)

    7.循环
    for i in 'hello':
      print(i)

    需要掌握的操作(****)
    1、strip,lstrip,rstrip
    msg='*****hello****'
    print(msg.strip('*'))#去*
    print(msg.lstrip('*'))#去左边*
    print(msg.rstrip('*'))#去右边*

    2、lower,upper
    msg='AaBbCc123123123'
    print(msg.lower())#字母变大写
    print(msg.upper())字母变小写

    3、startswith,endswith
    msg='alex is dsb'
    print(msg.startswith('alex'))#以alxe开头
    print(msg.endswith('sb'))#以sb结尾

    4、format的三种玩法
    msg='my name is %s my age is %s' %('egon',18)
    print(msg)

    msg='my name is {name} my age is {age}'.format(age=18,name='egon')
    print(msg)

    了解
    msg='my name is {} my age is {}'.format(18,'egon')
    msg='my name is {0}{0} my age is {1}{1}{1}'.format(18,'egon')
    print(msg)


    5、split,rsplit
    cmd='get|a.txt|33333'
    print(cmd.split('|',1))#从左边第一个|开始拆分
    print(cmd.rsplit('|',1))#从右边第一个|开始拆分


    6、replace#替换
    msg='kevin is sb kevin kevin'
    print(msg.replace('kevin','sb',2))

    7、isdigit #当字符串内为纯数字时结果为True
    res='11111'
    print(res.isdigit())
    int(res)

    age_of_bk=18
    inp_age=input('your age: ').strip()
    if inp_age.isdigit():
      inp_age=int(inp_age)
      if inp_age > 18:
          print('too big')
      elif inp_age < 18:
          print('to small')
      else:
          print('you got it')
    else:
      print('必须输入纯数字')
       
    了解(**)
    1、find,rfind,index,rindex,count
    print('xxxkevin is sb kevin'.find('kevin'))
    print('xxxkevin is sb kevin'.index('kevin'))
    print('xxxkevin is sb kevin'.rfind('kevin'))
    print('xxxkevin is sb kevin'.rindex('kevin'))

    print('kevin is kevin is kevin is sb'.count('kevin'))

    2、center,ljust,rjust,zfill
    print('egon'.center(50,'*'))
    print('egon'.ljust(50,'*'))
    print('egon'.rjust(50,'*'))
    print('egon'.zfill(50))

    3、captalize,swapcase,title
    print('my name is kevin'.capitalize())
    print('AaBbCc'.swapcase())
    print('my name is kevin'.title())

    4、is其他
    name='egon123'
    print(name.isalnum()) #字符串由字母或数字组成
    print(name.isalpha()) #字符串只由字母组成

    print(name.islower())
    print(name.isupper())
    name='   '
    print(name.isspace())
    msg='I Am Egon'
    print(msg.istitle())




    ======================================该类型总结====================================
    存一个值

    有序

    不可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)
    x='aaa'
    print(id(x))
    x='bbb'
    print(id(x))

     

    三.列表类型

    列表类型list

    ======================================基本使用======================================
    1、用途:记录多个值(同种属性)

    2、定义方式:在[]内用逗号分隔开多个任意类型的值
    l=['a','b','c'] #l=list(['a','b','c'])

    类型转换
    l=list('hello')
    l=list({'x':1,'y':2})
    print(l)

    3、常用操作+内置的方法
    优先掌握的操作:
    l=['a','b','c','d','e']
    1、按索引存取值(正向存取+反向存取):即可存也可以取

    print(l[0])
    print(l[-1])
    print(id(l))
    l[0]='A'
    print(id(l))

    l[4]='EEEEEE'
    print(l)

    2、切片(顾头不顾尾,步长)
    l=['a','b','c','d','e']
    print(l[1:4])
    print(l)

    3、长度
    l=['a','b','c','d','e']
    print(len(l))

    4、成员运算in和not in
    print('a' in l)
    print('ssssss' not in l)

    5、追加&插入
    l=['a','b','c','d','e']
    l.append(3333333)
    l.append(44444)
    print(l)

    l.insert(0,11111111111)
    print(l)

    6、删除
    l=['a','b','c','d','e']
    del l[0]
    res=l.remove('b')#none
    print(l)
    print(res)

    res=l.pop(0)#输出删除了的那个值
    print(l)
    print(res)

    7、循环
    l=['a','b','c','d','e']
    for item in l:
      print(item)
       
    需要掌握的操作
    l=['a','b','a','c','d','e']
    print(l.count('a'))

    l=['a','b','a','c','d','e']
    items=[1,2,3,4,5]
    for item in items:
      l.append(item)
    print(l)
    或者用一行代码 l.extend(items)#extend在末尾加上所有值,append是加一个值

    l=['a','b','a','c','d','e']
    l.reverse()#反过来排序
    print(l)

    l=[10,-1,3,11,9]
    l.sort(reverse=True) #从小到大排列,加了括号里面的就是从大到小排列
    print(l)
    ======================================该类型总结====================================
    存多个值

    有序

    可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)

    练习题
    1. 队列:先进先出
    l=[]
    # 入队
    l.append('first')
    l.append('second')
    l.append('third')
    print(l)
    出队
    print(l.pop(0))
    print(l.pop(0))
    print(l.pop(0))

    2. 堆栈:后进先出
    l=[]
    入栈
    l.append('first')
    l.append('second')
    l.append('third')
    print(l)
    出栈
    print(l.pop())
    print(l.pop())
    print(l.pop())#括号里面默认的是-1

    四.元组类型

    元组tuple:

    ======================================基本使用======================================
    1、用途:元组就是一个不可变的列表

    2、定义方式:在()内用逗号分隔开多个任意类型的元素
    t=(1,2.2,'aa',('b','c'),['a','b','c']) # t=tuple(...)
    print(type(t))
    强调:
    l=['a']
    print(type(l),l[0])

    t=('a',)
    print(type(t))
    print(t)

    msg=('hello world')


    类型转换
    t1=tuple('hello')
    t2=tuple([1,2,3])
    print(t1)
    print(t2)

    3、常用操作+内置的方法
    优先掌握的操作:
    t=(1,2.2,'aa',('b','c'),['a','b','c'])
    1、按索引取值(正向取+反向取):只能取
    print(t[0])
    print(t[-1])

    2、切片(顾头不顾尾,步长)
    t=('a','b','c','e','f')
    print(t[1:4])

    3、长度
    print(len(t))

    4、成员运算in和not in
    print('a' in t)

    5、循环
    for item in t:
      print(item)

    需要掌握的操作
    t=('a','b','c','e','a','f')
    print(t.index('a',1,5))
    print(t.count('a'))
    ======================================该类型总结====================================
    存多个值

    有序

    不可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)
    t=('a','b','c')
    print(id(t))
    t=('A','B','C')
    print(id(t))

    五.字典类型

    字典类型dict

    ======================================基本使用======================================
    1、用途:记录多个值,列表是索引对应值,而字典是key对应值,其中key对value有描述性的功能

    2、定义方式:在{}用逗号分隔开多个元素,每个元素都是key:value的形式,其中key可以不可变类型,通常是字符串类型
    而value可以是任意类型
    d={1:'aaa',2.2:'bbb','xxx':'ccc',(1,2,3):'dddd'} #d=dict(...)
    print(d[(1,2,3)])

    类转换
    d=dict(x=1,y=2,z=3)
    print(d)

    items=[('name','egon'),('age',18),('gender','male')]
    d={}
    for item in items:
      d[item[0]]=item[1]

    d=dict(items)
    print(d)

    了解
    keys=['name','age','gender','height','weight']
    d={}
    for key in keys:
      d[key]=None
    也可用一行代码:
    d={}.fromkeys(keys,None)
    print(d,type(d))

    3、常用操作+内置的方法
    优先掌握的操作:
    1、按key存取值:可存可取
    dic={'name':'egon','age':18}
    print(dic.get('name'))

    print(dic['name'])
    dic['name']='EGON'
    dic['gender']='male'
    print(dic)

    dic={'name':'egon','age':18}
    print(dic)
    print(len(dic))

    3、成员运算in和not in :是以字典的key为准的
    dic={'name':'egon','age':18}
    print('name' in dic)
    print('egon' in dic)


    4、删除
    dic={'name':'egon','age':18}
    del dic['name']
    print(dic)

    res=dic.pop('name')
    print(dic)
    print(res)

    res=dic.popitem()
    print(res)

    5、键keys(),值values(),键值对items()
    在python2
    >>> dic={'name':'egon','age':18}
    >>>
    >>>
    >>> dic.keys()
    ['age', 'name']
    >>>
    >>>
    >>> dic.values()
    [18, 'egon']
    >>>
    >>>
    >>> dic.items()
    [('age', 18), ('name', 'egon')]

    在python3
    >>> dic={'name':'egon','age':18}
    >>>
    >>> dic.keys()
    dict_keys(['name', 'age'])
    >>> dic.values()
    dict_values(['egon', 18])
    >>> dic.items()
    dict_items([('name', 'egon'), ('age', 18)])
    6、循环
    dic={'name':'egon','age':18}
    for k in dic:
      print(k)

    for k in dic.keys():
      print(k)

    for v in dic.values():
      print(v)

    for k,v in dic.items(): #k,v=('name', 'egon')
      print(k,v)
       
    需要掌握的操作
    dic={'name':'egon','age':18}
    dic.update({'age':19,'gender':'male'})
    print(dic)    
    dic={'name':'egon','age':18}
    #当key存在时,不改原值,返回原值
    res=dic.setdefault('name','EGON')
    print(dic)
    print(res)
    # 当key不存在时,增加新值
    res=dic.setdefault('gender','male')
    print(dic)
    print(res)
    ======================================该类型总结====================================
    存多个值

    无序

    可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值

    六.集合类型

    集合类型

    ======================================基本使用======================================
    1、用途:I: 关系运算 II:去重

    2、定义方式:在{}内用逗号分隔开多个元素,但是元素的特点是
    I: 集合内的元素必须是不可变类型
    II: 集合内元素无序
    III: 集合内元素不能重复

    s={1,'aaa',2,} #s=set(...)
    print(s,type(s))

    s=set()
    print(s,type(s))

    s={1,1,1,1,1,1,1,1,1,1,1,1,'a','a','a'}
    print(s)

    数据类型转换
    res=set('hello')
    print(res)

    res=set([1,'a','b'])
    print(res)

    3、常用操作+内置的方法
    优先掌握的操作:
    1、长度len
    2、成员运算in和not in

    pythons={'张铁蛋','李铜淡','王金蛋','赵银胆','alex','kevin'}
    linuxs={'oldboy','张铁蛋','赵银胆','alex','wxx'}
    3、|合集:求所有报名的学生
    print(pythons | linuxs)
    print(pythons.union(linuxs))

    4、&交集:求同时报名两门课程的学生
    print(pythons & linuxs)

    5、-差集: 求只报名python课程的学员
    print(pythons - linuxs)
    print(linuxs - pythons) #求只报名linux课程的学员

    6、^对称差集:求没有同时报名两门课程的学生
    res=(pythons - linuxs) | (linuxs - pythons)
    res=pythons ^ linuxs
    print(res)

    7、==
    s1={1,2,3}
    s2={3,2,1}
    print(s1 == s2)

    注意:父子集描述的是一种包含与被包含的关系
    8、父集:>=
    9、子集:<=
    s1={1,2,3}
    s2={1,2,3,4}
    print(s2 >= s1)
    print(s1 <= s2)

    需要掌握的
    s1={1,2,3}
    s1.update({3,4,5,6})#去重并集
    print(s1)

    s1={1,'aa','bb',3}
    print(s1.pop())#随机删除

    res=s1.remove('bb')#只能删除集合中0有的元素,删没有的会报错
    print(s1)
    print(res)

    s1.discard('bbb')#删没有的不会报错
    s1.add(4)
    print(s1)

    s1.add(4)#在集合中增加值
    print(s1)
    ======================================该类型总结====================================
    存多个值

    无序

    可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)


    集合的去重
    局限性
    1. 只能针对不可变类型
    2. 不能保证原来的顺序
    names=['egon','egon','egon','alex','alex','kevin']

    new_names=list(set(names))
    print(new_names)
    l=[
      {'name':'egon','age':18,'sex':'male'},
      {'name':'alex','age':73,'sex':'male'},
      {'name':'kevin','age':20,'sex':'female'},
      {'name':'egon','age':18,'sex':'male'},
      {'name':'egon','age':18,'sex':'male'},
    ]
    new_l=[]
    for dic in l:
      if dic not in new_l:
          new_l.append(dic)

    print(new_l)
  • 相关阅读:
    socket的使用一
    logging模块
    configparser模块
    python中read() readline()以及readlines()用法
    hashlib
    JavaScript中forEach的用法相关
    循环调用是事件绑定中遇到的一些问题
    javascript 中 offsetWidth,clientWidth;offsetHeight,clientHeight的区别
    javascript事件:获取事件对象getEvent函数
    html标签之meta标签
  • 原文地址:https://www.cnblogs.com/liubinliuliu/p/10014776.html
Copyright © 2011-2022 走看看