一、 列表、元组
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))) #出现次数
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
shoplist_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")
shoplist_by_self1 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 天生去重
dictionary_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) #有一个将字典转化成列表的过程,速度慢
dictionary21 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)
程序练习
程序: 三级菜单
要求:
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
three_level_menu1 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和学Linux的人可能重复,统计报名人数时需要去重(去重)。混在一块之后把两个班都报了的人再分出来,取列表中的交集(关系测试)。)
1 list_1=[1,4,5,7,3,6,7,9] 2 list_1=set(list_1) #转换为集合,自动去重,集合也是无序的 3 print(list_1,type(list_1)) 4 5 list_2=set([2,6,0,66,22,8,4]) 6 print(list_2,type(list_2)) 7 print("-----------") 8 print(list_1.intersection((list_2))) #取交集 9 print(list_1&list_2) 10 print("-----------") 11 print(list_1.union(list_2)) #取并集 12 print(list_1|list_2) 13 print("-----------") 14 print(list_1.difference(list_2)) #取差集,取1里有2里没有的 15 print(list_1-list_2) 16 print(list_2.difference(list_1)) #取差集,取2里有1里没有的 17 print(list_2-list_1) 18 print("-----------") 19 print(list_1.issubset(list_2)) #判断是否为子集 20 print(list_1.issuperset(list_2)) #判断是否为父集 21 list_3=set([1,3,7]) 22 print(list_3.issubset(list_1)) 23 print(list_1.issuperset(list_3)) 24 print("-----------") 25 print(list_1.symmetric_difference(list_2)) #对称差集,去掉两个的交集 26 print(list_1^list_2) 27 print("-----------") 28 print(list_2.isdisjoint(list_3)) #没有交集返回为True 29 print("-----------------------") 30 list_1.add(999) 31 print(list_1) #添加一项 32 list_1.update([888,777,555]) 33 print(list_1) #添加多项 34 print("-----------") 35 list_1.remove(999) 36 print(list_1) #删除一项,该元素不存在的话会报错 37 # print(list_1.pop()) #任意删除一项 38 list_1.discard(3232) 39 print(list_1) #指定删除,该元素不存在不会报错,但remove会报错
五、文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
1 # data=open("yesterday",encoding="utf-8").read() # 打开文件,但不能修改 2 3 '''d=open("yesterday","r",encoding="utf-8") #文件句柄(文件内存对象),可操作 4 data=d.read() 5 data2=d.read() 6 print(data) 7 print("---------data2-----------",data2) #执行第二遍,从上次结束的地方继续读,所以data2后面没东西了,类似光标''' 8 '''f=open("yesterday2","w",encoding="utf-8") #创建一个文件,可以写,但覆盖之前的文件,以前的内容没了 9 f.write("我爱北京天安门,\n") 10 f.write("天安门上太阳升")''' 11 12 '''f=open("yesterday2","a",encoding="utf-8") # a 追加, 13 f.write("\n我爱北京天安门....\n") 14 f.write("天安门上太阳升....")''' 15 16 '''f=open("yesterday2","a",encoding="utf-8") 17 f.write("\nwhen i was young i listen to the radio\n") #a追加,不覆盖原来的文件,也不可读 18 data=f.read() 19 print("---read",data)''' 20 21 '''f=open("yesterday","r",encoding="utf-8") 22 print(f.readline()) 23 print(f.readline()) 24 print(f.readline()) #读前三行,但写代码尽量避免重复的代码''' 25 '''f=open("yesterday","r",encoding="utf-8") 26 for i in range(3): 27 print(f.readline().strip())''' 28 #f.readlines #列表 29 '''f=open("yesterday","r",encoding="utf-8") 30 for line in f.readlines(): 31 print(line.strip())''' 32 33 '''f=open("yesterday","r",encoding="utf-8") 34 for index,line in enumerate(f.readlines()): #f.readlines()只适合读小文件,大文件费时间 35 if index ==9: 36 print("----我是分割线----") 37 continue 38 print(line.strip())''' #low loop 39 '''#high bige 40 count=0 41 f=open("yesterday","r",encoding="utf-8") 42 for line in f: # f变为了迭代器 43 if count==9: 44 print("----我是分割线----") 45 count += 1 46 continue 47 print(line.strip()) #打印一行,内存中删除一行,不占内存 48 count += 1 49 ''' 50 '''f=open("yesterday","r",encoding="utf-8") 51 print(f.tell()) #打印当前位置 52 print(f.readline()) 53 print(f.tell()) 54 f.seek(10) #回到的位置 55 print(f.readline()) 56 57 print(f.encoding) #打印文件的编码 58 59 print(f.fileno()) #返回内存中的编号(不是地址)与操作系统有关。不常用 60 61 print(f.flush()) # 强制刷新,不存到缓存''' 62 '''f=open("yesterday","r",encoding="utf-8") 63 print(f.truncate())# 不写就是清空,写数字就是从开头截断多少个字符,移动光标seek也是从开头截断''' 64 65 '''f=open("yesterday","r+",encoding="utf-8") #读写,可用 66 print(f.readline()) 67 print(f.readline()) 68 print(f.readline()) 69 f.write("----w----") #写到最后了 70 print(f.readline())''' 71 72 '''f=open("yesterday2","w+",encoding="utf-8") #写读,没什么卵用 73 f.write("----w----\n") 74 f.write("----w----\n") 75 f.write("----w----\n") 76 f.write("----w----\n") 77 print(f.tell()) 78 f.seek(11) 79 print(f.tell()) 80 print(f.readline()) 81 f.write("secondline") #还是追加到后面了''' 82 83 # f=open("yesterday","a+",encoding="utf-8") #追加读写,也是加在后面 84 85 '''f=open("yesterday2","rb") # 二进制文件 86 print(f.readline()) 87 print(f.readline()) # 网络传输(socket.py)只能用二进制格式传输 in Python3.x 88 # 下载的(视频等)文件,以字符的格式打开可能造成文件损坏''' 89 90 '''f=open("yesterday2","wb") 91 f.write("hello binary".encode("utf-8"))'''
1 f=open("yesterday","r",encoding="utf-8") 2 f_new=open("yesterday.bak","w",encoding="utf-8") 3 4 for line in f: 5 if "肆意的快乐等我享受"in line: 6 line=line.replace("肆意的快乐等我享受","肆意的快乐等jyh享受") 7 f_new.write(line) 8 f.close() 9 f_new.close() 10 11 f=open("yesterday","r",encoding="utf-8") 12 f_new=open("yesterday.bak","w",encoding="utf-8") 13 ''' 14 import sys 15 find_str=sys.argv[1] 16 replace_str=sys.argv[2] 17 for line in f: 18 if find_str in line: 19 line=line.replace(find_str,replace_str) 20 f_new.write(line) 21 f.close() 22 f_new.close() 23 ''' # 传参数替换
刷新(进度条)
1 import sys,time 2 for i in range(20): 3 sys.stdout.write("#") #不换行打印 4 sys.stdout.flush() 5 time.sleep(0.2)
程序练习
程序1: 实现简单的shell sed替换功能
程序2:修改haproxy配置文件
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1 f=open("yesterday","r",encoding="utf-8") 2 with open("yesterday","r",encoding="utf-8") as f: 3 for line in f: 4 print(line) #自动关闭文件
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
1 f=open("yesterday","r",encoding="utf-8") 2 f2=open("yesterday2","r",encoding="utf-8") 3 with open("yesterday","r",encoding="utf-8") as f,\ 4 open("yesterday2","r",encoding="utf-8") as f2: #一行不超过80个字符 5 for line in f: 6 print(line) #自动关闭文件
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
六、字符编码与转码
1 import sys 2 print(sys.getdefaultencoding()) #Python默认编码
详细文章:
http://www.cnblogs.com/yuanchenqi/articles/5956943.html
http://www.diveintopython3.net/strings.html
需知:
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
1 s="你好" 2 s_gbk=s.encode("gbk") #除了改编码集,还要变成bytes类型 3 print(s_gbk) 4 print(s.encode()) 5 6 gbk_to_utf8=s_gbk.decode("gbk").encode("utf-8") #decode告诉Unicode你是gbk,encode转成utf-8 7 print("utf8",gbk_to_utf8)
1 # -*-coding:gbk-*- #文件是gbk编码 2 # Author:JYH 3 4 s="你好" #这里还是unicode(默认的)编码 5 print(s.encode("gbk")) #显示的是gbk的编码格式 6 print(s.encode("utf-8" )) 7 print(s.encode("gb2312").decode("gbk"))

上图仅适用于py2
浙公网安备 33010602011771号