Python学习笔记_day2
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习笔记_day2相关的知识,希望对你有一定的参考价值。
一、 列表、元组
1 names=["A","B","C","D"] 2 print(names) 3 print(names[0],names[2]) 4 print(names[1:3]) # 包括起始位置,不包括结束位置,顾头不顾尾。这个动作叫切片。 5 print(names[-1]) 6 print(names[-1:-3]) # 切片从左到右 7 print(names[-2:]) # 取到最后 8 print(names[:3]) #从0取可以不写 9 10 names.append("E") #追加 11 print(names) 12 13 names.insert(1,"F") #插入,1表示插入的位置 只能一个一个来,不能批量插入 14 print(names) 15 names.insert(3,"G") 16 print(names) 17 18 names[2]="H" # 改 19 print(names) 20 21 #delete 22 ‘‘‘names.remove("F") 23 print(names)‘‘‘ 24 ‘‘‘del names[1] 25 print(names)‘‘‘ 26 ‘‘‘names.pop(1) # 不输入下标删掉最后一个‘‘‘ 27 print(names) 28 print(names.index("H")) 29 print(names[names.index("H")]) 30 31 names.append("A") # 可以重名 32 print(names.count("A")) 33 34 ‘‘‘names.clear() # 清空 35 print(names)‘‘‘ 36 37 names.reverse() 38 print(names) #反转 39 40 names.sort() #排序:#!>1>C>c 按ASCII码排序来的 41 print(names) 42 43 names2=[1,2,3,4] 44 names.extend(names2) #并过来 45 print(names,names2) 46 del names2 #删除列表names2,print(names2)报错 47 print(names) 48 49 names3=names.copy() #复制 50 print(names3) 51 52 names[2]="三" 53 print(names) 54 print(names3)
1 import copy 2 3 names=["A","B","C",["E","F"],"D"] 4 print(names) 5 6 names2=copy.deepcopy(names) #copy.copy(names)和浅copy一样,深copy用处不大,知道就行 7 print(names,names2,sep="\n") 8 print(id(names),id(names2),sep="\n") 9 10 11 names[3][0]="MM" 12 print(names,names2,sep="\n")
1 names=["A","B","C",["E","F"],"D"] 2 print(names) 3 4 names2=names.copy() #names2=name还跟简单的str和数字不同,names2跟着names变 5 print(names2) 6 7 names[2]="三" 8 print(names,names2,sep="\n") 9 10 names[3][0]="MM" 11 print(names,names2,sep="\n") #只copy第一层 ,改names2也一样 12 13 names2[3][0]="GG" 14 print(names,names2,sep="\n")
1 names=["A","B","C",["M","G"],"D","E"] 2 3 for i in names: 4 print(i) 5 6 #切片 7 #range(1,10,2) 8 print(names[0:-1:2]) 9 print(names[::2]) 10 print(names[:])
test.py:1、sys模块是Python解释器自带的用C语言写的,所以找不到。2、浅copy是引用列表。
1 import copy 2 person=["name",["salary",100]] 3 4 ‘‘‘p1=copy.copy(person) 5 p2=person[:] 6 p3=list(person) 7 print(p1,p2,p3,sep="\n")‘‘‘#三种浅copy方法 8 9 p1=person[:] 10 p2=person[:] 11 12 p1[0]="alex" 13 p2[0]="fengjie" 14 15 p1[1][1]=50 #浅copy可以用来创建联合账号,共同存款的变化,但实际上不会这样用。 16 17 print(p1) 18 print(p2)
元组不能更改,可理解为只读列表。两种方法:count、index
1 names=(("alex","jack"),(1,2),(8,9),(1,2),[6,7]) 2 print(names.index((8,9))) #查询位置 3 print(names.count((1,2))) #出现次数
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
1 ‘‘‘shoplist=[[1,"Iphone",5800],[2,"Macbook",12000],[3,"Surfacelaptop",8888],[4,"Bike",800],[5,"Coffe",30]] 2 salary=int(input("Enter integer salary of you:")) 3 4 for i in shoplist: 5 print(i) 6 buy=input("Choose something you like and enter the serial number:") 7 if buy==1: 8 if salary>shoplist[0][3]: 9 salary=salary-shoplist[0][3] 10 print("You have chosen the",shoplist[0][2]) 11 else: 12 print("Your balance is not enough") 13 elif buy==2: 14 if salary>shoplist[1][3]: 15 salary=salary-shoplist[1][3] 16 print("You have chosen the",shoplist[1][3]) 17 else: 18 print("Your balance is not enough")‘‘‘ 19 #以上为自己编写的错误的思路 20 21 product_list=[("Iphone",5800), 22 ("Mac Pro",9800), 23 ("Bike",800), 24 ("Watch",10600), 25 ("Coffee",31), 26 ("Alex Python",120)] 27 shopping_list=[] 28 while True: 29 salary=input("Input your salary:") 30 if salary.isdigit(): #判断是不是数字 31 salary=int(salary) 32 while True: 33 for index,item in enumerate(product_list): #enumerate把列表下标直接取出来 34 #print(product_list.index(item),item) 35 print(index+1,".",item,sep="") 36 user_choice=input(‘‘‘Choose something you like and enter the serial number (You can press "q "to quit)>>>:‘‘‘) 37 if user_choice.isdigit(): 38 user_choice=int(user_choice) 39 if user_choice<=len(product_list) and user_choice>=1: 40 p_item=product_list[user_choice-1] 41 if p_item[1]<=salary:#买得起 42 shopping_list.append(p_item) 43 salary -=p_item[1] 44 print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m"%(p_item,salary)) #\033[31;1m...\033[0m 加颜色 45 else: 46 print("\033[31;1m你的余额只剩 %s 啦,还买个毛线!\033[0m"%salary) 47 else: 48 print("product code [%s] is not exist!"%user_choice) 49 elif user_choice=="q": 50 print("------shopping list------") 51 for p in shopping_list: 52 print(p) 53 print("Your current balane:",salary,"\nThank for your shopping and looking forward to your next visit!") 54 exit() 55 else: 56 print("Invalid option") 57 else: 58 print("Please enter an integer")
1 product_list=[["Iphone",5800],["MacBook",8000],["Surfacelaptop",9999],["Iwatch",10000],["ThinkPad",12000]] 2 shoplist=[] 3 while True: 4 salary = input("Enter your salary:") 5 if salary.isdigit(): 6 salary=int(salary) 7 while True: 8 for item in product_list: 9 print(product_list.index(item)+1,".",item,sep="") 10 users_choice=input("Choose something you like\nEnter the sequence number to buy" 11 "(You can press the ‘q‘ to quit) --->:") 12 if users_choice.isdigit(): 13 users_choice = int(users_choice) 14 if users_choice<=len(product_list) and users_choice>=1: 15 if product_list[users_choice-1][1]<=salary: 16 shoplist.append(product_list[users_choice-1]) 17 salary=salary-product_list[users_choice-1][1] 18 print("Your current balance:",salary) 19 else: 20 print("你的钱只剩%s了,还买个毛线!"%salary) 21 exit() 22 else: 23 print("Invalid option") 24 elif users_choice == "q": 25 print("------shoplist------") 26 for i in shoplist: 27 print(i) 28 print("Your curren balance:%s"%salary) 29 print("Looking forward your next shopping!") 30 exit() 31 else: 32 print("Invalid option") 33 else: 34 print("Please enter an integer!")
二、字符串操作
特性:不可修改
1 name="my\tname is {name} and i am {year} years old" 2 print(name.capitalize())#首字母大写 3 print(name.count("a"))#统计字母出现次数 4 print(name.center(50,"-")) #居中 5 print(name.endswith("ang")) #判断字符串是不是以..结尾 6 print(name.expandtabs(tabsize=30)) #\t 加空格 7 print(name[name.find("name"):]) #find找字符串位置,字符串也可以切片,用法与列表一样 8 print(name.format(name="jyh",year=24)) 9 print(name.format_map({"name":"jyh","year":24})) #字典 10 print("ab23".isalnum()) #阿拉伯的数字和字符 11 print("ac".isalpha()) #纯英文字符 12 print("1A".isdecimal()) #判断十进制,没什么用 13 print("1A".isdigit()) #判断整数 14 print("A1".isidentifier())#判断是不是一个合法的标识符 15 print("a1".islower())#判断小写 16 print("1/3".isnumeric())#判断整数,没什么用 17 print(" ".isspace())#判断空格 18 print(" My Name Is ".istitle())#判断每个首字母是否大写 19 print(" My Name Is ".isprintable())#判断是否可以打印,用的很少 tty file,drive file 20 print(" My Name Is ".isupper())#判断大写 21 print("+".join(["1","2","3"])) #连接字符串,经常用 22 print(name.ljust(50,"*")) #长度50,不够在后面用*补 23 print(name.rjust(50,"-")) #长度50,不够在前面用-补 24 print("Alex".lower()) #大写变小写 25 print("Alex".upper()) #小写变大写 26 print("\n Alex".lstrip()) #从左去掉空格后回车,rstrip同理,strip用得最多 27 28 p=str.maketrans("abcdef",‘123456‘) #类似数字对应,必须一样多 29 print("alex li".translate(p)) #用的不多 30 31 print("alex li".replace("l","L",1)) #替换 32 print("alex lil".rfind("l")) #从左往右,找到最后面值的下标 33 print("alex lil".split("l")) #按分隔符"l"将字符串分成列表 34 print("1+2+3+4".split("+")) #按分隔符"+"将字符串分成列表 35 print("1+2\n+3+4".splitlines()) #按换行符(识别不同系统的换行符)将字符串分成列表 36 print("Alex Li".swapcase()) #大小写互换 37 print("AleX Li".title()) #首字母变大写 38 print("AleX Li".zfill(50)) #没什么用
三、字典操作
字典一种key - value(键-值) 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。
字典的特性:
- dict是无序的
- key必须是唯一的,so 天生去重
1 #key-value 键-值 2 info = { 3 ‘stu1101‘: "A", 4 ‘stu1102‘: "B", 5 ‘stu1103‘: "C", 6 } 7 8 print(info) #字典是无序的 9 print(info["stu1101"]) #取值,查找 10 info["stu1101"]="D" #改 11 info["stu1104"]="E" #创建 12 #del info["stu1101"] 13 #info.pop("stu1101") 14 #info.popitem() #随机删,别用,无意义 15 print(info) 16 17 print(info["stu1101"]) #查找,没有的话出错 18 print(info.get("stu1105"))#查找,没有的话打印None 19 print("stu1107" in info) #查找,没有的话打印False #info.has_key("1107") in python2.x 20 21 b={"stu1101":"Alex",1:3,2:5} 22 info.update(b) # 有交叉的key覆盖,没有的话创建 23 print(info) 24 25 print(info.items()) #把字典转成列表 26 27 c=dict.fromkeys([6,7,8],[1,{"name":"alex"},444]) #初始化一个新的字典 28 print(c) 29 c[7][1]["name"]="Jack Chen" 30 print(c) # 三个Key共享一个内存地址,也就是都会变成"Jack Chen" 31 32 for i in info: 33 print(i,info[i]) 34 35 for k,v in info.items(): 36 print(k,v) #有一个将字典转化成列表的过程,速度慢
1 av_catalog = { 2 "A":{ 3 "A1": ["A11","A12"], 4 "A2": ["A21","A22"], 5 "A3": ["A31","A32"], 6 "A4":["A41","A42"] 7 }, 8 "B":{ 9 "B1":["B11","B12"] 10 }, 11 "C":{ 12 "C1":["C11","C12"] 13 } 14 } 15 16 av_catalog["C"]["C1"][1]="C13" 17 print(av_catalog) 18 av_catalog.setdefault("C",{"C11":[1,2]}) 19 print(av_catalog) 20 av_catalog.setdefault("D",{"C11":[1,2]}) #先到字典去key,取到返回,取不到,重新加一个 21 print(av_catalog)
程序练习
程序: 三级菜单
要求:
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
1 data={ 2 ‘北京‘:{ 3 "昌平":{ 4 "沙河":["oldboy","test"], 5 "天通苑":["链家地产","我爱我家"], 6 }, 7 "朝阳":{ 8 "望京":{"奔驰","陌陌"}, 9 "国贸":{"CICC","HP"}, 10 "东直门":{"Advent","飞信"}, 11 }, 12 "海淀":{}, 13 }, 14 ‘山东‘:{ 15 "德州":{}, 16 "青岛":{}, 17 "济南":{}, 18 }, 19 ‘广东‘:{ 20 "东莞":{}, 21 "常熟":{}, 22 "佛山":{}, 23 }, 24 } 25 exit_flag=False 26 while not exit_flag: 27 for i in data: 28 print(i) 29 choice=input("选择进入1>>>:") 30 if choice in data: 31 while not exit_flag: 32 for i2 in data[choice]: 33 print("\t",i2) #\t为了区分级别加空格 34 choice2 = input("选择进入2>>>:") 35 if choice2 in data[choice]: 36 while not exit_flag: 37 for i3 in data[choice][choice2]: 38 print("\t\t", i3) 39 choice3 = input("选择进入3>>>:") 40 if choice3 in data[choice][choice2]: 41 for i4 in data[choice][choice2][choice3]: 42 print("\t\t\t",i4) 43 choice4 = input("最后一层,按b返回>>") 44 if choice4=="b": 45 pass #占位符,否则报错 46 elif choice4=="q": 47 exit_flag=True 48 if choice3 == "b": 49 break 50 elif choice3 == "q": 51 exit_flag = True 52 if choice2 == "b": 53 break 54 elif choice2 == "q": 55 exit_flag = True 56 elif choice == "q": 57 exit_flag = True
以上是关于Python学习笔记_day2的主要内容,如果未能解决你的问题,请参考以下文章