重点:
- 多个数据储存到单变量,分成列表:[...]、元组(...)、字典{...}。其中元组只读不能修改,类似于C++的enum;字段需要在里面自定义索引{"index1":'Content'}.
- python中变量复制的关系不同于C++,C++中变量复制对每个都分配内存(除了设定指针),但python会节省内存设定指针.
tuple:
#元组,不能修改,又叫只读列表 names=('a1','a2','a3','a4') #1、count():查找元素在tuple中出现的次数。 #2.index():查找元素的第一个索引值。 print(names.count('a1')) print(names.index('a4'))
variance and copy:
import copy #浅copy本质上是引用,只能第一层复制,列表中的列表只复制指针 var1=['name',['a',100]] #引用的三种方式 p1=copy.copy(var1)#string会新建立内存,但是列表只复制指针 p2=var1[:] #string会新建立内存,但是列表只复制指针 p3=list(var1) #string会新建立内存,但是列表只复制指针 print(p1,p2,p3) p4=p1 #若直接用=,则建立指针 p1[0]='abc' #只修改p1,不影响p2,p3,但影响p4 p2[0]='def' #只修改p2,不影响p1,p3 p3[1][0]="ABC" #指向的内容修改,影响其他 print(p1,p2,p3,p4)
import:
import sys print(sys.path) # 打印环境变量 print(sys.argv) # 打印当前脚本路径 import os cmd_res = os.system("dir") # 执行win命令,不保存结果 print("-->", cmd_res) cmd_res = os.popen("dir").read() # 保存结果 print("-->", cmd_res) # os.mkdir("test") #在当前脚本所在目录创建目录
data type:
#python中数据类型:int,float,complex print(type(10*24)) print(type(23.123465789)) print(type(5+4j)) #python中虚数用j表示,不同于数学用i表示.
三元运算:
#三元运算 a,b,c=100,200,300 d=a if a>b else c print(d) e= 100 if 200>1000 else 200 print(e)
16进制,byte与str:
#16进制表示法 ''' 后缀:H 前缀:0x ''' #python3中 byte字节与str字符串是区分的,两者可以转换 print('€20'.encode('utf-8')) #.encode():str转二进制byte print(b'\xe2\x82\xac20'.decode('utf-8')) #.decode():byte转str msg = '我爱北京天安门' print(msg) print(msg.encode('utf-8')) print(msg.encode('utf-8').decode('utf-8'))
列表的一些操作:
# Author:Zhang Yuan names = 'A1 A2 A3 A4' print(names) names=['A1','A2','A3','A4'] print(names[0],names[2]) print(names[1]+' '+names[2]) #切片(顾头不顾尾) print(names[1:3]) print(names[0:2]) print(names[3:]) #取后面的 print(names[-2:]) names.append("A5") #追加一个到最后 print(names) names.insert(1,"A1.5") #插入到指定位置 print(names) names[1]='A1.55' #修改 print(names) #delete names.remove("A2") print(names) del names[1] print(names) names.pop(2) print(names) #查找元素 print(names.index("A5")) print(names[names.index("A5")]) #列表有相同元素 names.append("A3") #追加一个到最后 print(names) print(names.count("A3")) #返回列表中多少个指定元素 names.reverse() #列表翻转 print(names) names.sort() #排序列表 names2=[1,2,3,4] names.extend(names2) #合并列表name2到name1末尾 #del names2 #删除列表name2 #列表中可以再追加列表,追加列表本质是追加指针 names.append(["B1","B2"]) names2 = names.copy() #普通copy只能复制第一层 import copy names3=copy.deepcopy(names) #深度copy相当于重新建立内存 names[-1].append("B3") #指针指向的列表追加的数据,所以下面names,names2两个变量都显示变化 print(names,names2,names3) #不同于c++数组,python内存和变量的关系与c++不同!!! a=[1,2,3] #分配内存,a指向数据 b=a #b也指向a指向的数据 c=a.copy()#复制,新增加内存储存数据 a[-1]=66 #通过a修改内存数据 print(a,b,c) #所以b变化,c不变 a[0]=66 #通过a修改内存数据 print(a,b,c) #所以b变化,c不变 a=[1,2,3] #a重新赋值,相当于重新分配内存,但是b指向的内存依然不变 print(a,b,c) #所以b不变,c不变 #列表的有步长的切片 print(names,names[0::2]) #从开始到末尾,包括末尾 print(names,names[::2]) #0可以省略 #列表的循环 for i in names: print(i) #清空列表 #names.clear() #print(names)
string的一些操作:
# Author:Zhang Yuan name="my \tname is {name} and I am {year}" print(name.capitalize()) print(name.count("a")) print(name.center(50,"-")) print(name.endswith("an")) print(name.expandtabs(tabsize=30)) print(name[name.find("name"):]) print(name.format(name='ZhangYuan',year='30')) print(name.format_map( {"name":"ZhanXiang","year":33} )) print("AB123".isalnum()) print("AB123".isalpha()) print("1A".isdecimal()) #判断是否为十进制 print('A1'.isidentifier()) #判断是否为合法的标识符 print("33".isnumeric()) print(" ".isspace()) print("My Name Is".istitle()) print("My Name Is".isprintable()) #tty file,drive file print("MY NAME".isupper()) print("+".join(["1","2","a"])) print(name.ljust(50,'*')) print(name.rjust(50,'*')) print("ABCDE,ASF".lower()) print("ABCDE,ASF,asdfadsfg".upper()) print(' \nabcdasdf'.lstrip()) #从左边开始去除空格和回车 print('asdf \n '.rstrip()) print(' \n asdf \n '.strip()) print("abcde".translate(str.maketrans("abcefg","123456"))) print('alex li'.replace("1",'L',1)) print('alex li'.rfind("l")) print("123.132.321".split(".")) print('1+2\n+3+4'.splitlines()) print("Acd".swapcase()) print("fdsa erf df".title()) print('asdfdsa'.zfill(20))
购物车(自己版本):
# Author:Zhang Yuan goods1=['G1',256] goods2=['G2',300] goods3=['G3',400] goods4=['G4',123] goods5=['G5',56] goods6=['G6',321] wallet=1000 ShoppingCart=[] print('your wallet have $', wallet) while (wallet > 56): buy=input("what do you want to buy? G1-G6 or Stop") if buy==goods1[0]: goods=goods1 if wallet>goods[1]: ShoppingCart.append(goods1) wallet=wallet-goods[1] print("your shopping carts are:",ShoppingCart,' your wallet have',wallet) else: print("your need$", goods[1], 'but your have $', wallet) elif buy==goods2[0]: goods=goods2 if wallet>goods[1]: ShoppingCart.append(goods2) wallet=wallet-goods[1] print("your shopping carts are:",ShoppingCart,' your wallet have',wallet) else: print("your need$", goods[1], 'but your have $', wallet) elif buy==goods3[0]: goods=goods3 if wallet>goods[1]: ShoppingCart.append(goods3) wallet=wallet-goods[1] print("your shopping carts are:",ShoppingCart,' your wallet have',wallet) else: print("your need$", goods[1], 'but your have $', wallet) elif buy==goods4[0]: goods=goods4 if wallet>goods[1]: ShoppingCart.append(goods4) wallet=wallet-goods[1] print("your shopping carts are:",ShoppingCart,' your wallet have',wallet) else: print("your need$", goods[1], 'but your have $', wallet) elif buy==goods5[0]: goods=goods5 if wallet>goods[1]: ShoppingCart.append(goods5) wallet=wallet-goods[1] print("your shopping carts are:",ShoppingCart,' your wallet have',wallet) else: print("your need$", goods[1], 'but your have $', wallet) elif buy==goods6[0]: goods=goods6 if wallet>goods[1]: ShoppingCart.append(goods6) wallet=wallet-goods[1] print("your shopping carts are:",ShoppingCart,' your wallet have',wallet) else: print("your need$",goods[1],'but your have $',wallet) elif buy=='Stop': print('your stop buy by yourself') print("your shopping carts are:", ShoppingCart, ' your wallet have', wallet) break else: print("your have spend most of your money, your can't buy any more")
购物车(其他版本):
# Author:Zhang Yuan product_list=[ ('Iphone',5800), ('Mac Pro',9800), ('Watch',10600), ('Coffee',30), ('Book',120) ] shopping_list=[] salary = input('Input your salary:') #判断输入的字符串是否为数字 if salary.isdigit()==True: salary=int(salary) while True: #普通的索引方式 ''' for item in product_list: print(product_list.index(item),item) ''' #enumerate相当于枚举式的索引,单独一个变量中存储“序号和内容” ''' for item in enumerate(product_list): print(item) ''' #两个变量分别存储:index-序号、item-内容 for index,item in enumerate(product_list): print(index,item) user_choice=input('what do you want to buy? or q?') if user_choice.isdigit()==True: user_choice=int(user_choice) #len()返回列表的长度 if user_choice<len(product_list) and user_choice>=0: p_item=product_list[user_choice] if p_item[1]<=salary: shopping_list.append(p_item) salary-=p_item[1] print('Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m' %(p_item,salary)) else: print('\033[41;1mYour salary only have %s\033[0m'%salary) else: print('product code [%s] is not exist'%user_choice) elif user_choice=="q": print('------shopping list---') for p in shopping_list: print(p) print('your current balance:',salary) exit() else: print('invalid input')
字典的使用:
# Author:Zhang Yuan #key-value info={ 'stu1101':'A1', 'stu1102':'A2', 'stu1103':'A3', } info2={ 'stu1101':'B1', '123':'456' } info.update(info2)#相同索引覆盖,新索引添加 print(info) print(info['stu1101']) print(info.get('stu1105')) #这种方式不会出错 print(info.get('stu1102')) info['stu1101']='B1' info['stu1104']='Add' print(info) #delete del info['stu1101'] info.pop('stu1104') print(info) #dictionary嵌套 av_catalog={ "Euro":{ "index1":["www.youporn.com","Free,General Quality"], "index2":["www.pornhub.com","Free,High Quality"], "index3":["letmedothistoyou.com","self"], "index4":["x-art.com","Very High Quality,Not Free"] }, "Japan":{ "index1":["tokyo-hot"] }, "China":{ "index1":["1024"] } } av_catalog["China"]["index1"][0]='ABCDE' print(av_catalog.values()) print(av_catalog["Euro"].keys()) av_catalog.setdefault("TaiWan",{"index1":["www.baidu.com"]}) #setdefault()当没有时创建,当有时不变 av_catalog.setdefault("China",{"index1":["www.baidu.com"]}) #setdefault()当没有时创建,当有时不变 print(av_catalog) print(info) print(info.items()) c=dict.fromkeys([6,7,8],[1,{"index1":"abc"},444])#共同指向一个地址 print(c) c[7][1]['index1']='def'#修改一个则全部修改 print(c) for i in av_catalog: print(i,av_catalog[i]) #字典转列表,如果数据量大要很久 for k,v in av_catalog.items(): print(k,v)
三级菜单:
# Author:Zhang Yuan data={ "AnHui":{ "HeFei":{ "FeiXi":"肥西", "FeiDong":"肥东" }, "LuAn":{ "YuAn":"裕安", "JinAn":"金安" } }, "ShangHai":{ "PuDong":{ "LuJiaZui":"陆家嘴" }, "XuHui":{ "XuJiaHui":"徐家汇" } }, } print(data["AnHui"]["LuAn"]["YuAn"]) while True: for i in data: print(i) choice=input("Choice to get in 1:") if choice in data: while True: for j in data[choice]: print("\t",j) choice2=input("Choice to get in 2:") if choice2 in data[choice]: while True: for k in data[choice][choice2]: print("\t\t",k) choice3=input("Choice to get in 3:") if choice3 in data[choice][choice2]: for l in data[choice][choice2][choice3]: print("\t\t\t", l) print("last get in,input b get out") elif choice3=="b": break elif choice2=="b": break elif choice=="b": break