day05-数据类型
阅读目录
一、简介
1 为什么有数据类型?
#现实生活中我们习惯于把物品分门别类,比如厨房用具放到厨房,衣服放进衣柜,卫生间放上洗漱用品,计算机上的也有各种我们经常使用的程序(看电影的mp4/avi、听音乐的mp3,处理文档的word)而数据类型就是我们用来分类数据的,以方便我们后期使用,数据用来表示状态的,不同的状态就应该用不同的类型的数据去表示。
2 怎么分类使用?
x=10,10是我们要存储的数据
#2.1 数据类型分类:
#数字(整形,长整形,浮点型,复数)
#字符串
#字节串:在介绍字符编码时介绍字节bytes类型
#列表
#元组
#字典
#集合
3 数据类型的学习方法
#======================================基本使用======================================
#1、用途:为什么要用?
#2、定义方式:怎么使用?(语法)
#3、常用操作+内置的方法
#======================================该类型总结====================================
#存一个值or存多个值
#有序or无序
#可变or不可变(1、可变:值变,id不变。可变==不可hash 2、不可变:值变,id就变。不可变==可hash)
#可变类型:值改变的情况下,id不变
#不可变类型:值改变的情况下,id也跟着改变
二、数字类型
2.1 整型与浮点型
#整型int
#1.1 用途:记录年龄、等级、身份证号,qq号等整型数字相关
#1.2 语法定义:age=10 #本质age=int(10)
#浮点型float
#1.2 用途:记录薪资,身高,体重,体质参数等浮点数相关
#2.2 语法定义:salary=3000.3 #本质salary=float(3000.3)
2.2 定义方式以及注意事项
# 2 定义方式
age=18 #age=int(18)
print(type(age))
int('abadf') #报错
int('10.1') #报错
int('101') #int只能将字符串中包含纯数字转成整型
2.3 常用操作+内置方法
#二进制,十进制,八进制,十六进制
# 十进制转成其他进制
print(bin(12))
print(oct(12)) #12 =>1*(8**1) + 2*(8**0)
print(hex(16))
# 进制转换(了解**)
# 其他进制转成十进制
print(int(10,2))
print(int(10,8))
print(int(10,16))
2.4 其他数字类型(了解)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#长整形(了解) 在python2中(python3中没有长整形的概念): >>> num=2L >>> type(num) <type 'long'> #复数(了解) >>> x=1-2j >>> x.real 1.0 >>> x.imag -2.0
三、字符串类型
3.1 为什么需要用字符串?
#用途:记录描述性的状态,比如人的名字、性别,国籍,地址等
3.2 怎么去定义?
#定义方式:在单引号('')\双引号("")\三引号("""""")内,由一串字符组成
name='Ryan'
msg='hello' #msg=str('hello')
res1=str(1)
res2=str([1,2,3])
print(type(res1),type(res2))
info="'xxx'"
3.3 常用的操作+内置方法
3.3.1 优先掌握的操作:
#优先掌握的操作:
#1、按索引取值(正向取+反向取) :只能取
#2、切片(顾头不顾尾,步长)
#3、长度len
#4、成员运算in和not in
#5、移除空白strip
#6、切分split
#7、循环
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#1、按索引取值(正向取+反向取) :只能取 msg='hello world' print(msg[4]) print(msg[-1]) msg[3]='A' # 报错 # 2、切片(顾头不顾尾,步长) msg='hello world' # 就是从一个大的字符串中切分出一个全新的子字符串 print(msg[0:5]) print(msg) # 没有改变原值 print(msg[0:5:1]) print(msg[0:5]) print(msg[0:5:2]) #hlo # 了解: print(msg[0:5:1]) msg='hello world' print(msg[5:0:-1]) print(msg[5::-1]) print(msg[-1::-1]) print(msg[::-1]) #3、长度len msg='hello world' print(len(msg)) #4、成员运算in和not in: 判断一个子字符串是否存在于一个大的字符串中 print('alex' in 'alex is dsb') print('dsb' in 'alex is dsb') print('sb' in 'alex is dsb') print('xxx' not in 'alex is dsb') # 推荐 print(not 'xxx' in 'alex is dsb') #5、去掉字符串左右两边的字符strip,不管中间的 user=' egon ' user=' x egon ' user="*******egon********" user=" **+* */***egon* **-*****" print(user.strip("* +/-")) user=input('>>>: ').strip() if user == "egon": print('用户名正确') #6、切分split:针对按照某种分隔符组织的字符串,可以用split将其切分成列表,进而进行取值 msg="root:123456:0:0::/root:/bin/bash" res=msg.split(':') print(res[1]) cmd='dowload|a.txt|3333333' cmd_name,filename,filesize=cmd.split('|') #7、循环 msg='hello' for item in msg: print(item)
3.3.2 需要掌握的操作
#1、strip,lstrip,rstrip
#2、lower,upper
#3、startswith,endswith
#4、format的三种玩法
#5、split,rsplit
#6、join
#7、replace
#8、isdigit
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 需要你掌握的
#1、strip,lstrip,rstrip
print('*****egon*****'.lstrip('*'))
print('*****egon*****'.rstrip('*'))
print('*****egon*****'.strip('*'))
#2、lower,upper
msg='aABBBBb'
res=msg.lower()
print(res)
print(msg)
#3、startswith,endswith
msg='alex is dsb'
print(msg.startswith('alex'))
print(msg.endswith('sb'))
print(msg.endswith('b'))
#4、format的三种玩法
print('my name is %s my age is %s' %('egon',18))
print('my name is {name} my age is {age}'.format(age=18,name='egon'))
# 了解
print('my name is {} my age is {}'.format(18,'egon'))
print('my name is {0} my age is {1}{1}'.format(18,'egon'))
#5、split,rsplit
msg='get|a.txt|333331231'
print(msg.split('|',1))
print(msg.rsplit('|',1))
#6、join
msg='get|a.txt|333331231'
l=msg.split('|')
print(l)
src_msg='|'.join(l)
print(src_msg)
#7、replace
msg='alex say i have one tesla,alex is alex hahaha'
print(msg.replace('alex','sb',1))
print(msg)
#8、isdigit # 判断字符串中包含的是否为纯数字
print('10.1'.isdigit())
age=input('>>: ').strip()
if age.isdigit():
age=int(age) #int('asfdsadfsd')
if age > 30:
print('too big')
elif age < 30:
print('too small')
else:
print('you got it')
else:
print('必须输入数字')
3.3.3 需要了解的内置方式
#1、find,rfind,index,rindex,count
#2、center,ljust,rjust,zfill
#3、expandtabs
#4、captalize,swapcase,title
#5、is数字系列
#6、is其他
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 需要了解的内置方法 #1、find,rfind,index,rindex,count msg='hello alex is sb' print(msg.find('alex')) print(msg.find('alex',0,3)) print(msg.index('alex')) print(msg.index('alex',0,3)) msg='alex aaa alex' print(msg.find('alex')) print(msg.rfind('alex')) msg='alex aaa alex' print(msg.count('alex')) # 统计一个子字符串在大字符串中出现的次数 #2、center,ljust,rjust,zfill print('egon'.center(50,'*')) print('egon'.ljust(50,'*')) print('egon'.rjust(50,'*')) print('egon'.zfill(50) #3、expandtabs print('a\tb'.expandtabs(1)) #4、captalize,swapcase,title print('hello'.capitalize()) print('hElLo'.swapcase()) print('egon is nb'.title()) #5、is数字系列 #在python3中 num1=b'4' #bytes num2=u'4' #unicode,python3中无需加u就是unicode num3='壹' #中文数字 num4='Ⅳ' #罗马数字 ''.isnumeric(): unicode,中文数字,罗马数字 print(num2.isnumeric()) print(num3.isnumeric()) print(num4.isnumeric()) ''.isdecimal(): unicode print(num2.isdecimal()) print(num3.isdecimal()) print(num4.isdecimal()) # ''.isdigit() :bytes,unicode print(num1.isdigit()) print(num2.isdigit()) print(num3.isdigit()) print(num4.isdigit()) #6、is其他 print('abc你'.isalpha()) # 字符串中包含的是字母或者中文字符 # 字符串中包含的是字母(中文字符)或数字 print('ab'.isalnum()) print('123123'.isalnum()) print('ab123'.isalnum()) #二:该类型总结 # 1 存一个值 # 2 有序 # 3 不可变
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#1、find,rfind,index,rindex,count s = 'kevin is dsb o and kevin is sb' # print(s.find('dsb')) # 返回的是d字符所在的索引值 # print(s.find('xxx')) # 找不到的时候不报错返回的是-1 # print(s.find('i',0,3)) # 还可以通过索引来限制查找范围 # print(s.index('o')) # 返回所传字符所在的索引值 # print(s.index('i',0,3)) # 返回所传字符所在的索引值 # print(s.count('n')) # 统计字符出现的次数 #2、center,ljust,rjust,zfill s9 = 'jason' # print(s9.center(12,'*')) # print(s9.ljust(40,'$')) # print(s9.rjust(40,'$')) # print(s9.rjust(40,' ')) # print(s9.zfill(40)) #3、expandtabs # s10 = 'a\tbc' # print(s10.expandtabs(100)) #4、captalize,swapcase,title # s12 = 'hElLo WoRLD sH10' # print(s12.capitalize()) # Hello world 首字母大写 # print(s12.swapcase()) # 大小写互换 # print(s12.title()) # 每个单词的首字母大小 #5、is数字系列 num1=b'4' #bytes num2=u'4' #unicode,python3中无需加u就是unicode num3='壹' #中文数字 num4='Ⅳ' #罗马数字 # ''.isnumeric(): unicode,中文数字,罗马数字 只要是表示数字都识别 print(num2.isnumeric()) print(num3.isnumeric()) print(num4.isnumeric()) # ''.isdecimal(): unicode 只识别普通的阿拉伯数字 print(num2.isdecimal()) print(num3.isdecimal()) print(num4.isdecimal()) # ''.isdigit() :bytes,unicode 通常情况下使用isdigit就已经满足需求了 print(num1.isdigit()) print(num2.isdigit()) print(num3.isdigit()) print(num4.isdigit())
练习
# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " aleX"
# 1) 移除 name 变量对应的值两边的空格,并输出处理结果
# 2) 判断 name 变量对应的值是否以 "al" 开头,并输出结果
# 3) 判断 name 变量对应的值是否以 "X" 结尾,并输出结果
# 4) 将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
# 5) 将 name 变量对应的值根据 “l” 分割,并输出结果。
# 6) 将 name 变量对应的值变大写,并输出结果
# 7) 将 name 变量对应的值变小写,并输出结果
# 8) 请输出 name 变量对应的值的第 2 个字符?
# 9) 请输出 name 变量对应的值的前 3 个字符?
# 10) 请输出 name 变量对应的值的后 2 个字符?
# 11) 请输出 name 变量对应的值中 “e” 所在索引位置?
# 12) 获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分) name = " aleX" # 1) 移除 name 变量对应的值两边的空格,并输出处理结果 name = ' aleX' a=name.strip() print(a) # 2) 判断 name 变量对应的值是否以 "al" 开头,并输出结果 name=' aleX' if name.startswith(name): print(name) else: print('no') # 3) 判断 name 变量对应的值是否以 "X" 结尾,并输出结果 name=' aleX' if name.endswith(name): print(name) else: print('no') # 4) 将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果 name=' aleX' print(name.replace('l','p')) # 5) 将 name 变量对应的值根据 “l” 分割,并输出结果。 name=' aleX' print(name.split('l')) # 6) 将 name 变量对应的值变大写,并输出结果 name=' aleX' print(name.upper()) # 7) 将 name 变量对应的值变小写,并输出结果 name=' aleX' print(name.lower()) # 8) 请输出 name 变量对应的值的第 2 个字符? name=' aleX' print(name[1]) # 9) 请输出 name 变量对应的值的前 3 个字符? name=' aleX' print(name[:3]) # 10) 请输出 name 变量对应的值的后 2 个字符? name=' aleX' print(name[-2:]) # 11) 请输出 name 变量对应的值中 “e” 所在索引位置? name=' aleX' print(name.index('e')) # 12) 获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。 name=' aleX' a=name[:-1] print(a)
四、列表类型
4.1 为什么需要列表?
#作用:多个装备,多个爱好,多门课程,多个女朋友,存放多个值,可以根据索引存取值
4.2 怎么去定义?
#定义方式:在[]内用逗号分割开多个任意类型的值
l=['apri','lxx','yxx'] # l=list(['apri','lxx','yxx'])
l1=list('hello') #list就相当于调用了一个for循环依次取出'hello'的值放入列表
print(l1)
l2=list({'x':1,'y':2,'z':3})
print(l2)
list(10000) # 报错
4.3 常用操作+内置的方法
4.3.1 优先掌握的操作
#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in
#5、追加
#6、往指定索引前插入值
#7、删除
#8、循环
#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取
l=['apri','lxx','yxx']
print(l[0])
l[0]='APRI'
print(l)
print(l[-1])
print(l[3])
l[0]='APRI' # 只能根据已经存在的索引去改值
l[3]='xxxxxxxx' #如果索引不存在直接报错
#2、切片(顾头不顾尾,步长)
l=['apri','lxx','yxx',444,555,66666]
print(l[0:5])
print(l[0:5:2])
print(l[::-1])
#3、长度
l=['apri','lxx','yxx',444,555,66666,[1,2,3]]
print(len(l))
#4、成员运算in和not in
l=['apri','lxx','yxx',444,555,66666,[1,2,3]]
print('lxx' in l)
print(444 in l)
#5、追加
l=['apri','lxx','yxx']
l.append(44444)
l.append(55555)
print(l)
#6、往指定索引前插入值
l=['apri','lxx','yxx']
l.insert(0,11111)
print(l)
l.insert(2,2222222)
print(l)
# 一次性添加多个元素
l = ['jason','nick']
l.extend(['tank','sean'])
#7、删除
l=['egon','lxx','yxx']
# 单纯的删除值:
# 方式1:
del l[1] # 通用的
print(l)
# 方式2:
res=l.remove('lxx') # 指定要删除的值,返回是None
print(l,res)
# 从列表中拿走一个值
res=l.pop(-1) # 按照索引删除值(默认是从末尾删除),返回删除的那个值
print(l,res)
#8、循环
l=['egon','lxx','yxx']
for item in l:
print(item)
4.3.2 需要掌握的操作
# 需要掌握的操作
l=['egon','egon','lxx','yxx',444,555,66666]
print(l.count('egon'))
print(l.index('egon'))
print(l.index('yxx',0,1))
l.clear()
items=['a','b','c']
items='hello'
for item in items:
l.append(item)
l.extend(items)
print(l)
l=['egon','egon','lxx','yxx',444,555,66666]
l.reverse()
print(l)
nums=[3,-1,9,8,11]
nums.sort(reverse=True)
print(nums)items=[1,'a','b',2items.sort()
#二:该类型总结
# 1 存多个值
#
# 2 有序
#
# 3 可变
l=['a','b','c']
print(id(l))
l.append('d')
print(id(l))
# 队列:先进先出
l=[]
# # 入队
l.append('first')
l.append('second')
l.append('third')
print(l)
# # 出队
print(l.pop(0))
print(l.pop(0))
print(l.pop(0))
# 堆栈:先进后出
l=[]
# 入栈
l.append('first')
l.append('second')
l.append('third')
print(l)
# 出栈
print(l.pop())
print(l.pop())
print(l.pop())
练习:
1. 有列表data=['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量
2. 用列表模拟队列
3. 用列表模拟堆栈
4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
{'name':'alex','age':84},
{'name':'oldboy','age':73},
{'name':'egon','age':18},
]
答案:
l.sort(key=lambda item:item['age'])
print(l)