Python学习之旅--第二周--元组字符串运算字典
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习之旅--第二周--元组字符串运算字典相关的知识,希望对你有一定的参考价值。
一、元组
另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改,比如同样是列出同学的名字:
# Author:Tim Gu tuple = ("Tim",‘Jack‘,‘mike‘)
元组元素不可被修改,只读。不过有一种情况是内嵌列表的时候,列表内的元素可修改
# Author:Tim Gu tuple = ("Tim",‘Jack‘,‘mike‘,[‘john‘,‘tom‘]) print(tuple) tuple[3][1] = ‘mary‘ print(tuple) >>> (‘Tim‘, ‘Jack‘, ‘mike‘, [‘john‘, ‘tom‘]) (‘Tim‘, ‘Jack‘, ‘mike‘, [‘john‘, ‘mary‘])
二、字符串
输入时的空格处理:
# Author:Tim Gu username = input(‘user:‘) if username.strip() == ‘Tim‘: #去除输入时的空格 print("welcome")
输出:
user: Tim
welcome
字符串的拆分与合成:
names = ‘Tim,jack,rain‘ name2 = names.split(",") #拆分 print(name2) print(",".join(name2)) #组合 >>> [‘Tim‘, ‘jack‘, ‘rain‘] Tim,jack,rain
判断字符串有没有空格
# Author:Tim Gu name = ‘Tim Gu‘ if ‘‘ in name: print(‘‘ in name) >>>True
字符串的格式化:format()
msg = "Hello, {name}, it‘s been a long {age} since time sopke..." msg2 = msg.format(name=‘Tim‘,age=30) print(msg2) >>> Hello, Tim, it‘s been a long 30 since time sopke...
msg2 = "hahaha{0}, ddd{1}" print(msg2.format("Tim",33)) >>> hahahaTim, ddd33
字符串切片
name = ‘tim gu‘ print(name[1:3]) #打印序列字符 print(name.center(40,‘-‘)) #填满40个字符 print(name.find(‘m‘)) #搜索字符串中的字符,返回的第一个找到的值的索引,没有找到返回-1 print(name.find(‘b‘)) >>> im -----------------tim gu----------------- 2 -1
判断输入是否数字
age = input(‘input you age:‘) if age.isdigit(): #判断输入是否是数字 age = int(age) else: print(‘Invalid data type‘) >>> age = input(‘input you age:‘) if age.isdigit(): #判断输入是否是数字 age = int(age) else: print(‘Invalid data type‘)
判断输入是否包含特殊字符
name = ‘Timsjl4‘ print(name.isalnum()) >>> True
字符特殊判断
name = ‘Timsjl4‘ print(name.endswith(‘jl4‘)) #判断是否jl4结尾 print(name.startswith(‘Tim‘)) #判断是否Tim开头 print(name.upper()) #大写 print(name.lower()) #小写 >>> True True TIMSJL4 timsjl4
三、运算:
运算符:
+ 加
- 减
* 乘
/ 除
** 幂
% 取摸--返回除法的余数
// 取整数---返回商的整数
比较运算:
== 等于
!= 不等于
>= 大于等于
<=小于等于
> 大于
< 小于
赋值运算:
= 赋值
+=加法赋值
-=减法赋值
*=乘法赋值
/=除法赋值
%=取模赋值
**=幂赋值
//取整除赋值
逻辑运算:
and 与---条件全为真返回True
or 或 -----条件有一个为True,返回True
not 布尔非
分身运算:
is 判断两个标识符是否引用自一个对象
is not 判断两个标识符是不是发引用不同对象
位运算:
& 按位与运算符
| 按位或运算符
^ 按位异或运算符
~ 按位取反运算符
<< 左移动运算符
>> 右移动运算符
四、字典
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
字典中的key必须是唯一的。
id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } print(id_db) id_db[9527][‘name‘] = ‘jeson‘ #修改key print(id_db[9527]) id_db[9531][‘wife_qq‘] = 59594399 #增加key和值 print(id_db[9531]) del id_db[9520][‘addr‘] #删除key和值 print(id_db[9520]) id_db[9527].pop(‘addr‘) #删除key和值 等同于上面的del print(id_db[9527])
输出:
{9520: {‘age‘: 23, ‘name‘: ‘Jack‘, ‘addr‘: ‘SuZhou‘}, 9531: {‘age‘: 30, ‘name‘: ‘Mike‘, ‘addr‘: ‘NanJing‘}, 9527: {‘age‘: 22, ‘name‘: ‘Tim‘, ‘addr‘: ‘ShangHai‘}} {‘age‘: 22, ‘name‘: ‘jeson‘, ‘addr‘: ‘ShangHai‘} {‘age‘: 30, ‘name‘: ‘Mike‘, ‘wife_qq‘: 59594399, ‘addr‘: ‘NanJing‘} {‘age‘: 23, ‘name‘: ‘Jack‘} {‘age‘: 22, ‘name‘: ‘jeson‘}
获取值:get()
# Author:Tim Gu id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } print(id_db) v = id_db.get(9531) #一般使用get获取值 #v = id_db[9531]#不建议使用这个 print(v)
输出:
{9520: {‘name‘: ‘Jack‘, ‘addr‘: ‘SuZhou‘, ‘age‘: 23}, 9531: {‘name‘: ‘Mike‘, ‘addr‘: ‘NanJing‘, ‘age‘: 30}, 9527: {‘name‘: ‘Tim‘, ‘addr‘: ‘ShangHai‘, ‘age‘: 22}} {‘name‘: ‘Mike‘, ‘addr‘: ‘NanJing‘, ‘age‘: 30}
update()
# Author:Tim Gu id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } dist2 = { 9527:{ ‘name‘:‘zhangsan‘, ‘age‘:10, ‘addr‘:‘JiangXi‘ } } print(id_db) id_db.update(dist2) print(id_db)
输出: 如果存在相同的key值,即覆盖。如不存在,则新建
{9520: {‘age‘: 23, ‘addr‘: ‘SuZhou‘, ‘name‘: ‘Jack‘}, 9531: {‘age‘: 30, ‘addr‘: ‘NanJing‘, ‘name‘: ‘Mike‘}, 9527: {‘age‘: 22, ‘addr‘: ‘ShangHai‘, ‘name‘: ‘Tim‘}} {9520: {‘age‘: 23, ‘addr‘: ‘SuZhou‘, ‘name‘: ‘Jack‘}, 9531: {‘age‘: 30, ‘addr‘: ‘NanJing‘, ‘name‘: ‘Mike‘}, 9527: {‘age‘: 10, ‘addr‘: ‘JiangXi‘, ‘name‘: ‘zhangsan‘}}
返回字典中的key或值,判断KEY是否存在:
# Author:Tim Gu id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } print(id_db) print(id_db.values()) print(id_db.keys()) print(9527 in id_db)
输出:
{9520: {‘addr‘: ‘SuZhou‘, ‘age‘: 23, ‘name‘: ‘Jack‘}, 9531: {‘addr‘: ‘NanJing‘, ‘age‘: 30, ‘name‘: ‘Mike‘}, 9527: {‘addr‘: ‘ShangHai‘, ‘age‘: 22, ‘name‘: ‘Tim‘}} dict_values([{‘addr‘: ‘SuZhou‘, ‘age‘: 23, ‘name‘: ‘Jack‘}, {‘addr‘: ‘NanJing‘, ‘age‘: 30, ‘name‘: ‘Mike‘}, {‘addr‘: ‘ShangHai‘, ‘age‘: 22, ‘name‘: ‘Tim‘}]) dict_keys([9520, 9531, 9527]) True
set.default():
# Author:Tim Gu id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } print(id_db.setdefault(9527)) #取一个key print(id_db.setdefault(9333,‘dddd‘)) #如果不存在,新增一个默认的key和值
输出:
{‘age‘: 22, ‘addr‘: ‘ShangHai‘, ‘name‘: ‘Tim‘} dddd
随机删除:popitem()
# Author:Tim Gu id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } print(id_db.popitem()) #随机删除一组数据 print(id_db)
输出:
(9520, {‘name‘: ‘Jack‘, ‘addr‘: ‘SuZhou‘, ‘age‘: 23}) {9531: {‘name‘: ‘Mike‘, ‘addr‘: ‘NanJing‘, ‘age‘: 30}, 9527: {‘name‘: ‘Tim‘, ‘addr‘: ‘ShangHai‘, ‘age‘: 22}}
字典转化为元组:items()
# Author:Tim Gu id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } print(id_db.items()) >>> dict_items([(9520, {‘name‘: ‘Jack‘, ‘age‘: 23, ‘addr‘: ‘SuZhou‘}), (9531, {‘name‘: ‘Mike‘, ‘age‘: 30, ‘addr‘: ‘NanJing‘}), (9527, {‘name‘: ‘Tim‘, ‘age‘: 22, ‘addr‘: ‘ShangHai‘})])
字典的循环:
# Author:Tim Gu id_db = { 9527:{ ‘name‘:‘Tim‘, ‘age‘:22, ‘addr‘:‘ShangHai‘ }, 9520:{ ‘name‘:‘Jack‘, ‘age‘:23, ‘addr‘:‘SuZhou‘ }, 9531:{ ‘name‘:‘Mike‘, ‘age‘:30, ‘addr‘:‘NanJing‘ } } for key in id_db: print(key,id_db[key])
输出:
9520 {‘age‘: 23, ‘name‘: ‘Jack‘, ‘addr‘: ‘SuZhou‘} 9531 {‘age‘: 30, ‘name‘: ‘Mike‘, ‘addr‘: ‘NanJing‘} 9527 {‘age‘: 22, ‘name‘: ‘Tim‘, ‘addr‘: ‘ShangHai‘}
五、集合 set
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
创建一个set
# Author:Tim Gu s = set({1,3,4,5}) s2 = {1,2,3,4} print(type(s)) print(s) print(type(s2)) print(s2) >>> <class ‘set‘> {1, 3, 4, 5} <class ‘set‘> {1, 2, 3, 4}
s2其实是调用了set()的构造方法
列表转化集合:
li = [11,22,11,22] s1 = set(li) print(s1)
输出:
{11, 22}
注意:集合是没有重复值的
集合添加元素:
se = {1,2,5,6,4} se.add(3) print(se) >>> {1, 2, 3, 4, 5, 6}
集合删除元素:
se = {1,2,5,6,4} se.remove(5) #删除,如果5不存在,报错
se.discard(2)#删除,如果2不存在,不报错 print(se) >>> {1, 4, 6}
集合是无序的无重复的元素的集合,所以两个set可以做交集、并集等操作:
se1 = {1,2,5,6,4} se2 = {5,6,8,3,44} print(se1&se2) print(se1|se2) >>> {5, 6} {1, 2, 3, 4, 5, 6, 8, 44}
差集:
s1 = {11,22,33} s2 = {22,33,44} s4 = {33,44,55} s3 = s1.difference(s2) print(s3) #s1中存在,s2中不存在 s3 = s1.symmetric_difference(s2) #d对称差集 print(s3) s1.difference_update(s2) #将s1更新为s1和s2的差集 print(s1)
输出:
{11} {11, 44} {11}
s1 = {11,22,33} s2 = {22,33,44} s1.symmetric_difference_update(s2) #将s1更新为s1和s2的对称差集 print(s1) >>> {11, 44}
pop移除:
s1 = {11,22,33} ret = s1.pop() #因集合是无序的,pop()会随机移除元素,将移除的元素赋给ret print(s1)
print(ret) >>> {11, 22}
33
并集:
s1 = {11,22,33} s2 = {22,33,44} s3 = s1.union(s2) print(s3) >>> {33, 22, 11, 44}
update()
s1 = {11,22,33} li = [11,22,3,11,2] s1.update(li) print(s1) s = ‘tim‘ s1.update(s) print(s1) >>> {3, 33, 2, 11, 22} {33, 2, 3, ‘t‘, ‘i‘, 11, ‘m‘, 22}
第二周练习:完美购物车
要求:
购物车:
用户启动程序后打印商品列表
允许用户选择购买商品
允许用户不断地购买各种商品
购买时检测 余额是否足够,如果足够,直接扣款 否则打印余额不足
允许用户主动退出程序,退出时打印已购商品列表
# Author:Tim Gu for i in range(3): salary = input(‘Input your salary:‘) if salary.isdigit(): salary = int(salary) break else: print(‘Invaild data type...‘) if i == 2: print(‘Wrong!‘) continue welcome_msg = ‘Welcome to Tim Shopping mall‘.center(50, ‘-‘) print(welcome_msg) exit_flag = False product_list = [ (‘Iphone‘,5888), (‘Mac Air‘,8000), (‘mac pro‘,9000), (‘xiaomi 2‘,19.2), (‘Coffer‘,30), (‘Tesla‘,820000), (‘Bike‘,700), (‘Cloth‘,200) ] shop_car = [] while exit_flag != True: print(‘product list‘.center(50,‘-‘)) for item in enumerate(product_list):#枚举元组 index = item[0] p_name = item[1][0] p_price = item[1][1] print(index,p_name,p_price) user_choice = input(‘[q=quit,c=check]What do you watn to buy?:‘) if user_choice.isdigit():#肯定是选择商品 user_choice = int(user_choice) if user_choice < len(product_list): p_item = product_list[user_choice] if p_item[1] <= salary: #资金够买 shop_car.append(p_item) salary -= p_item[1] print(‘Added [%s] into shop car,you current balance is \033[31;1m[%s]\033[0m‘%( p_item[0],salary)) else: print("Your balance is [%s],cannot afford this..."%salary) elif user_choice == ‘q‘ or user_choice == ‘quit‘: print("purchased products as below".center(40,‘*‘)) for item in shop_car: print(item) print("END".center(40,‘*‘)) print("Your balance is [%s] last"%salary) exit_flag = True elif user_choice == ‘c‘ or user_choice == ‘check‘: print("purchased products as below".center(40, ‘*‘)) for item in shop_car: print(item) print("END".center(40, ‘*‘)) print("Your balance is \033[41;1m[%s] last\033[0m" % salary)
作业需求:
作业需求: 1.优化购物程序,购买时允许用户选择购买多少件
2.允许多用户登陆,下一次登录后,继续按上次的余额继续购买(可以充值)
3.允许多户查看之间的购买记录(记录要显示商品购买时间)
4.商品列表分级展示,比如 第一层菜单: 1.家电类 2.衣服 3.手机类 4.车类
随便选择一个,比如车类,进入第2层
1.BMW X3 300000
2.AUDI Q5 350000
3.pasate 333335
4 tesla model_3 430000
5.tesla model_s 8888888
5.显示已购买商品时,如果有重复的商品,不打印多行,而是在一行展示
id p_name num total_price
1. TeslaModelS 2 35000000
2. coffee 4 10000
以上是关于Python学习之旅--第二周--元组字符串运算字典的主要内容,如果未能解决你的问题,请参考以下文章