python入门学习-day2
一、 学习数据类型的方法
- 二、 数字
- 三、字符串
- 四、列表
- 五、元组
- 六、字典
- 七、集合
- 八、数据类型总结
- 九、数据运算符
- 十、字符编码
- 十一、文件处理
- 十二、作业
一、 学习数据类型的方法
1.清楚什么是数据:
定义变量x=111,111是我们要存储的数据
2.为什么要这么多数据类型:
数据是用来表示状态的,不同的状态就应该用不同的类型的数据去表示
3.数据类型主要有:
数字(整形,长整形,浮点型,复数)
字符串
字节串:在介绍字符编码时介绍字节bytes类型
列表
元组
字典
集合
4.学习数据类型按照以下几个点展开学习:
#一:基本使用 1 用途 2 定义方式 3 常用操作+内置的方法 #二:该类型总结 1 存一个值or存多个值 只能存一个值 可以存多个值,值可以是什么类型的 2 有序or无序(是否存在索引排序) 3 可变or不可变 !!!可变:值变,id(内存地址)不变。可变==不可hash !!!不可变:值变,id(内存地址)就变。不可变==可hash
二、 数字
数字类型分为整型(int)和浮点型(float)
数字:只能存一个值,无序并且不可变类型
#整型int 作用:年纪,等级,身份证号,qq号等整型数字相关 定义方式: age=10 #本质age=int(10) #浮点型float 作用:薪资,身高,体重,体质参数等浮点数相关 salary=3000.3 #本质salary=float(3000.3) #二进制:只有0和1,逢2进1 #十进制:我们重用的阿拉伯数字0-9,逢10进1 #八进制:只有0-7,逢8进1 #十六进制:0,1,2,3,4,5,6,7,8,9,A(10),B(11),C(12),D(13),E(14),F(15) 逢16进1
其他数字类型:
#长整形(了解) 在python2中(python3中没有长整形的概念): >>> num=2L >>> type(num) <type 'long'> #复数(了解) >>> x=1-2j >>> x.real 1.0 >>> x.imag -2.0
三、 字符串型
作用:定义名字,性别,国籍,地址,以及描述事物信息等
定义方式:在单引号\双引号\三引号内,由一串字符组成,例如:
name = 'gr'
sex = "man"
字符串换行:cmd = '''
GGGGG
TTTTTT
NNNNN
'''
字符串:只能存一个值,有序(有索引排序)并且不可变类型
需要优先掌握有关字符串的操作:
#1.按索引取值(正向取和反向取):注意字符串只能取值 msg = '' hello word!" print(msg[0]) #输出值为h print(msg[0:3]) #区间取值,顾头不顾尾,实际输出msg[0],msg[1],msg[2] print(msg[1:]) #不写后区间表示直接读到字符串末尾值 print(msg[6:11:2]) #2代表步长间隔,后面的2表示每隔2个索引取一个值 print(msg[-1:-6:-1])#加负号表示读取方向变为倒向了,步长也要负号反向取 print(msg[-1::-1]) #从尾读到头,步长为1
#2.字符串切片(split),移除字符(strip):(也是顾头不顾尾,步长) aa=" gggg rrrr " res=aa.strip() print(res) #strip移除,默认不加参数就移除空格,去除两边的空格,中间的空格无法读取判定去除 bb = "*****gggg*****" res= bb,strip(*) print(res) #移除字符串中两边的*符号 #split切分,把一个字符串按照指定的分隔符切成一个列表 #strip,lstrip,rstrip print('*****egon*****'.strip('*')) print('*****egon*****'.lstrip('*'))#移除左边(left)的* print('*****egon*****'.rstrip('*'))#移除右边(right)的* #split,rsplit cmd='get|a.txt|3333' print(cmd.split('|',1)) #从左往右以|符号切割,步长为1 print(cmd.rsplit('|',1)) #从右往左以|符号切割,步长为1
#长度计算(len) name = "shenxian" print(len(name)) #输出字符串的长度 #成员运算in和not in name = "shenxiangrong" if sh in name: print() else: print() #判断字符是否在需要判定的字符串中
#循环: name = 'shenxian' for i in name: print(i) #循环输出name字符串中的每个字,根据索引遍历
需要掌握的字符串操作:
#1、lower,upper print('aaAbCCC'.lower()) #将字符串中的字母全部变成小写 print('aaAbCCC'.upper()) #将字符串中的字母全部变成大写 #2、startswith,endswith print('alex is sb'.startswith('alex')) #判断字符串是不是以alex开头 print('alex is sb'.endswith('sb')) #判断字符串是不是以sb结尾 #3、format的三种玩法 print('my name is %s my age is %s' % (18, 'egon')) 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}{0}{0} my age is {1}'.format(18, 'egon')) #4、join #join拼接,把列表拼接成字符串,列表中必须全部为字符串类型 #5、replace msg='my name is alex,alex say hello' print(msg.replace('alex','SB',1)) #其中的1代表替换从左往右数第几个需要替换的值 print(msg) #6、isdigit isdigit:只有在字符串中包含的是纯数字的情况下才结果才为True print('10123'.isdigit())
其他操作(了解即可)
#1、find,rfind,index,rindex,count #2、center,ljust,rjust,zfill #3、expandtabs #4、captalize,swapcase,title #5、is数字系列 #6、is其他
四、 列表
列表的作用:定义多个装备,多个爱好,多门课程,多个同一类型的值等
定义方式:
my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本质my_girl_friends=list([...]) #或 l=list('abc')
列表:可以存多个值,有序并且可变类型
需要优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取改 #ps:不能根据索引往列表里新加入值 l=['a','b','c','d'] print(l[3]) #正向取值 print(l[-1]) #反向取值 l[3] = 'D' #改值 print(l) #2、切片:从一个大列表中切出一个子列表(顾头不顾尾,步长) l=['a','b','c','d'] l1=l[1:3] print(l1) l2 = l[1:4:2] l3 = l[-1:-4:-2] #3、长度 l=['a','b','c','d'] print(len(l) #4、成员运算in和not in names=['egon','alex','wxx',1,3,4] print(4 in names) print(5 not in names) #5、追加,插入 l=['a','b','c','d'] l.append('aaa') print(l) l.insert(0,'B') #['B', 'a', 'b', 'c', 'd'] l.insert(0,'egon') print(l) #6、删除 l=['a','b','alex','d','alex'] del l[2] # 非字符串独有的删除,是一种通用的删除方式 print(l) l.remove('alex') # 单纯的删除,没有返回值 print(l) # 从列表中拿走一个值: #1、删除一个元素 #2、将该元素当做返回值返回 res=l.pop() # 默认从最后一个删除 print(l) print(res) res=l.pop(2) print(res) #7、循环 l=['a','b','c'] for item in l: print(item)
练习:
#队列:先进先出 li = [] for i in range(3): inp = input(">>>>:") li.append(inp) for i in li: print(i) #堆栈:先进后出 li = [] for i in range(3): inp = input(">>>>:") li.insert(0,inp) for i in li: print(i)
#ps:反向步长 l=[1,2,3,4,5,6] #正向步长 l[0:3:1] #[1, 2, 3] #反向步长 l[2::-1] #[3, 2, 1] #列表翻转 l[::-1] #[6, 5, 4, 3, 2, 1]
五、元组
作用:存多个值,对比列表来说,元组不可变(可当作字典的key),主要用于读
定义方式(将列表的[]换成()):
age=(11,22,33,44,55)本质age=tuple((11,22,33,44,55))
可存多个值,有序不可变类型
需要优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取 #2、切片(顾头不顾尾,步长) #3、长度 #4、成员运算in和not in #5、循环
六、字典
作用:存多个值,以key-value的形式存取,取值速度快
定义方式:{key:value, ......, .......} key必须为不可变类型,value可以是任意类型
info={'name':'dr','age':18,'sex':'man'} #本质info=dict({....})
字典属于可以存多个值,可变的,由于存在key的定义,所以没有有序或者无序之说
需要优先掌握的操作:
#1、按key存取值:可存可取 info={'name':'gt','age':18,'sex':'male'} prin(info['age']) #输出值为18 #2、长度len len(info) #3、成员运算in和not in #判断这个值是否存在字典中的value中 #4、删除 remove del#5、键keys(),值values(),键值对items() #6、循环
练习:
1、 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
a={'k1':[],'k2':[]}
c=[11,22,33,44,55,66,77,88,99,90]
for i in c:
if i>66:
a['k1'].append(i)
else:
a['k2'].append(i)
print(a)
2、统计s='hello alex alex say hello sb sb'中每个单词的个数
结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
#方法一: s='hello alex alex say hello sb sb' l=s.split() dic={} for item in l: if item in dic: dic[item]+=1 else: dic[item]=1 print(dic) #方法二: s='hello alex alex say hello sb sb' dic={} words=s.split() print(words) for word in words: #word='alex' dic[word]=s.count(word) print(dic)
#利用setdefault解决重复赋值 ''' setdefault的功能 1:key存在,则不赋值,key不存在则设置默认值 2:key存在,返回的是key对应的已有的值,key不存在,返回的则是要设置的默认值 d={} print(d.setdefault('a',1)) #返回1 d={'a':2222} print(d.setdefault('a',1)) #返回2222 ''' s='hello alex alex say hello sb sb' dic={} words=s.split() for word in words: #word='alex' dic.setdefault(word,s.count(word)) print(dic)
七、 集合
作用: 去重和关系运算
定义方式:
#{}大括号中,字符以逗号隔开 l = {"gr", "cp", "st", "zc"} k = {"xx", "jj", "rr", "st", "gr"}
集合是可以存储多个值,无序不可变类型
注意:
集合:可以包含多个元素,用逗号分割,
集合的元素遵循三个原则:
1:每个元素必须是不可变类型(可hash,可作为字典的key)
2:没有重复的元素
3:无序
集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值
需要优先掌握的操作:
l = {"gr", "cp", "st", "zc"}
k = {"xx", "jj", "rr", "st", "gr"}
#1、长度len
#2、成员运算in和not in
#3、两个集合的交集:
print(l & k)
#4、两个集合的差集:
print(l - k)
print(k - l)
#5、两个集合的并集:
print(l | k)
#6、两个集合的对称差集,即没同时在两个集合里面的成员:
print(l ^ k)
#7、==
#8、父集:>,>=
#9、子集:<,<=
练习:
#去重,无需保持原来的顺序 l=['a','b',1,'a','a'] print(set(l)) #去重,并保持原来的顺序 #方法一:不用集合 l=[1,'a','b',1,'a'] l1=[] for i in l: if i not in l1: l1.append(i) print(l1) #方法二:借助集合 l1=[] s=set() for i in l: if i not in s: s.add(i) l1.append(i) print(l1) #同上方法二,去除文件中重复的行 import os with open('db.txt','r',encoding='utf-8') as read_f,\ open('.db.txt.swap','w',encoding='utf-8') as write_f: s=set() for line in read_f: if line not in s: s.add(line) write_f.write(line) os.remove('db.txt') os.rename('.db.txt.swap','db.txt') #列表中元素为可变类型时,去重,并且保持原来顺序 l=[ {'name':'egon','age':18,'sex':'male'}, {'name':'alex','age':73,'sex':'male'}, {'name':'egon','age':20,'sex':'female'}, {'name':'egon','age':18,'sex':'male'}, {'name':'egon','age':18,'sex':'male'}, ] # print(set(l)) #报错:unhashable type: 'dict' s=set() l1=[] for item in l: val=(item['name'],item['age'],item['sex']) if val not in s: s.add(val) l1.append(item) print(l1) #定义函数,既可以针对可以hash类型又可以针对不可hash类型 def func(items,key=None): s=set() for item in items: val=item if key is None else key(item) if val not in s: s.add(val) yield item print(list(func(l,key=lambda dic:(dic['name'],dic['age'],dic['sex']))))
八、 数据类型总结
按存储空间的占用分(从低到高)
数字 字符串 集合:无序,即无序存索引相关信息 元组:有序,需要存索引相关信息,不可变 列表:有序,需要存索引相关信息,可变,需要处理数据的增删改 字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改
按存值个数区分
| 标量/原子类型 | 数字,字符串 |
| 容器类型 | 列表,元组,字典 |
按可变不可变区分
| 可变 | 列表,字典 |
| 不可变 | 数字,字符串,元组 |
按访问顺序区分
| 直接访问 | 数字 |
| 顺序访问(序列类型) | 字符串,列表,元组 |
| key值访问(映射类型) | 字典 |
九、运算符
#身份运算(is ,is not) is比较的是id,而双等号比较的是值 毫无疑问,id若相同则值肯定相同,而值相同id则不一定相同 >>> x=1234567890 >>> y=1234567890 >>> x == y True >>> id(x),id(y) (3581040, 31550448) >>> x is y False
详情可以参考我老师的文章:http://www.cnblogs.com/linhaifeng/articles/5935801.html#_label34
十、字符编码
这块老师讲得很详细,博客也写的很完美,大家可以参考一下:
http://www.cnblogs.com/linhaifeng/articles/5950339.html
十一:文件处理
https://www.cnblogs.com/VxiaoG/articles/9302253.html
十二:作业
#作业一: 三级菜单 #要求: 打印省、市、县三级菜单 可返回上一级 可随时退出程序
menu = { "上海":{"黄浦":{"局门路":{"社区食堂":"大排面","美食广场":"冒菜","笼百味":"稀饭"}}}, "成都":{"双流":{"老街区":{"百味品":"小汤包","廖记棒棒鸡":"辣毛肚","怪味餐厅":"干锅鸭"}}}, "大连":{"科技园":{"理工":{"兰州面馆":"牛肉面","外婆家饭":"羊肉串","惠人春饼":"薄春饼"}}} } tag = True while tag: for i in menu: print(i) choice1 = input('请选择第一层(如果要退出请按"q"):').strip() if choice1 == "q": print("退出成功!") break if choice1 not in menu: print("菜单中没有,请重新输入:") continue #第一层处理结束 while tag: menu1 = menu[choice1] for i in menu1: print(i) choice2 = input('请选择二层菜单(输入"q"退出程序,输入"b"返回上一层):').strip() if choice2 == "b": print("返回成功!") break if choice2 == "q": print("退出成功!") tag = False break if choice2 not in menu1: print("菜单中没有,请重新输入:") continue #第二层处理结束 while tag: menu3 = menu[choice1][choice2] for i in menu3: print(i) choice3 = input('请选择三层菜单(输入"q"退出程序,输入"b"返回上一层):').strip() if choice3 == "b": print("返回成功!") break if choice3 == "q": print("退出成功!") tag = False break if choice3 not in menu3: print("菜单中没有,请重新输入:") continue #第三层处理完成 while tag: menu4 = menu[choice1][choice2][choice3] for i in menu4: print(i) choice4 = input('请选择四层菜单(输入"q"退出程序,输入"b"返回上一层):').strip() if choice4 == "b": print("返回成功!") break if choice4 == "q": print("退出成功!") tag = False break if choice4 not in menu4: print("菜单中没有,请重新输入:") continue #第四层处理完成
#作业二:请闭眼写出购物车程序 #需求: 用户名和密码存放于文件中,格式为:egon|egon123 启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序 允许用户根据商品编号购买商品 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 可随时退出,退出时,打印已购买商品和余额
import os product_list = [['Iphone7',5800], ['Coffee',30], ['疙瘩汤',10], ['Python Book',99], ['Bike',199], ['ViVo X9',2499], ] shopping = {} #count = 0 # usrtotal = [] # passwdtotal = [] # file = open("use.txt","r") # for line in file: # list = str(line).split('|') # usrtotal.append(list[0]) # list1 = list[1].strip("\n") # passwdtotal.append(list1) # print(usrtotal) # print(passwdtotal) #print(type(list)) #print(list) while True: print(''' 1>>登陆 2>>注册 3>>购物 ''') choice = input("请选择操作方式:").strip() if choice == '1': tag = True count = 0 while tag: if count >= 3: print("登陆次数过多") break use = input("请输入用户名:").strip() passwd = input("请密码用户名:").strip() file = open("use.txt","r") for line in file: line = line.strip("\n") print(line) user_info = line.split(',') print(user_info) uname_of_db = user_info[0] pwd_of_db = user_info[1] balance_of_db = int(user_info[2]) if use == uname_of_db and passwd == pwd_of_db: print("登陆成功") # 登陆成功则将用户名和余额添加到列表 current_userinfo = [uname_of_db, balance_of_db] print('用户信息为:', current_userinfo) tag = False break else: print('用户名或密码错误') count += 1 elif choice == '2': user = input("请输入注册用户名:").strip() password = input("请输入你的密码:").strip() password1 = input("请再次输入你的密码:").strip() while True: if password == password1: break else: print('两次输入密码不一致,请重新输入!!!') balance = input('请输入充值金额:').strip() file = open("use.txt", "a+") file.write('%s,%s,%s\n' % (user, password, balance)) file.close() elif choice == '3': if len(current_userinfo) == 0: print('请先登陆...') else: #登陆成功后,开始购物 uname_of_db=current_userinfo[0] balance_of_db=current_userinfo[1] print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %( uname_of_db, balance_of_db )) tag = True while tag: for product, price in enumerate(product_list): #enumerate枚举这个列表的数据 print(product, price) choice = input('输入商品编号购物,或者输入q退出>>: ').strip() if choice.isdigit(): #isdigit方法判读choice这个字符串是否由数字组成 choice = int(choice) #把choice转化为整型 if choice < 0 or choice >= len(product_list): continue pname = product_list[choice][0] pprice = product_list[choice][1] if balance_of_db > pprice: if pname in shopping: # 原来已经购买过 shopping[pname]['count'] += 1 else: shopping[pname] = {'pprice': pprice, 'count': 1} balance_of_db -= pprice # 扣钱 current_userinfo[1] = balance_of_db # 更新用户余额 print( "Added product %s into shopping cart, myour current balance %s " % pname % balance_of_db) else: print("余额不足! 产品价格是{price},你还差{lack_price}".format( price=pprice, lack_price=(pprice - balance_of_db) )) print(shopping_cart) elif choice == 'q': print(""" ---------------------------------已购买商品列表--------------------------------- id 商品 数量 单价 总价 """) total_cost = 0 for i, key in enumerate(shopping): print('%22s%18s%18s%18s%18s' % ( i, key, shopping[key]['count'], shopping[key]['pprice'], shopping[key]['pprice'] * shopping[key]['count'] )) total_cost += shopping[key]['pprice'] * shopping[key]['count'] print(""" 您的总花费为: %s 您的余额为: %s ---------------------------------end--------------------------------- """ % (total_cost, balance_of_db)) while tag: inp = input('确认购买(yes/no?)>>: ').strip() if inp not in ['Y', 'N', 'y', 'n', 'yes', 'no']: continue if inp in ['Y', 'y', 'yes']: # 将余额写入文件 src_file = file dst_file = r'%s.swap' % file with open(src_file, 'r', encoding='utf-8') as read_f, \ open(dst_file, 'w', encoding='utf-8') as write_f: for line in read_f: if line.startswith(uname_of_db): l = line.strip('\n').split(',') l[-1] = str(balance_of_db) line = ','.join(l) + '\n' write_f.write(line) os.remove(src_file) os.rename(dst_file, src_file) print('购买成功,请耐心等待发货') shopping_cart = {} current_userinfo = [] tag = False else: print('输入非法') else: print('非法操作')

浙公网安备 33010602011771号