python基礎篇 day2
阿新 • • 發佈:2017-10-03
++ nal 去除 and 黃河 技術分享 ase ror date
1.list 列表
#增加 append insert name = [‘0alex‘,‘1jack‘,‘2snow‘,‘3pig‘] print(name) name.append(‘4snake‘) #追加到末尾 print(name) name.insert(1,‘xxxx‘) #插入到下標為1的位置 name.insert(3,‘qqqq‘) print(name)
#更改下標對應元素 #打印下標對應元素 #循環打印list元素 name1 = [‘0alex‘,‘1jack‘,‘2snow‘,‘3pig‘] name1[2] = ‘update‘ print(name1) print(name1[0]) print(name1[3]) print(name1[-1]) #倒數第一個 打印 print(name1[-2]) #倒數第2個 打印 for i in name1: #循環打印list元素 print(i)
#正向切片 name2 = [‘0alex‘,‘1jack‘,‘2snow‘,‘3pig‘,‘4dog‘] print(name2) print(name2[0:3]) #切片[0,3) print(name2[:3]) #切片[0,3) print(name2[0:-1]) #切片[0,-1) 除了倒數第一個都打印 #反向切片 name3 = [‘0alex‘,‘1jack‘,‘2snow‘,‘3pig‘,‘4dog‘] print(name3) print(name3[-1:-3]) #打印為空[] -1是最後一個 print(name3[-3:-1]) #[-3,-1) #步長切片 print(name2[0:-1:2]) #[‘0alex‘, ‘1jack‘, ‘2snow‘, ‘3pig‘] #[‘0alex‘, ‘2snow‘]
#索引(獲取下標) 和統計 name4 = [‘0alex‘,‘1jack‘,‘2snow‘,‘3pig‘,‘4dog‘,‘4dog‘] print(name4) print(name4.index(‘1jack‘)) #獲取元素對應的下標 print(name4[name4.index(‘1jack‘)]) #獲取元素對應的下標,下標對應的元素 print(name4.count(‘4dog‘)) #統計幾個4dog
#刪除 name4.remove(‘4dog‘) #刪除 print(name4) del name4[1] #刪除下標1的 print(name4) name4.pop(2) #刪除下標2的 name4.pop() #刪除,默認下標-1的 print(name4)
#翻轉 排序 name5 = [‘0alex‘,‘1jack‘,‘2snow‘,‘3pig‘,‘4dog‘] name5.reverse() #翻轉 print(name5) name5.sort() #排序 print(name5)
#擴展 age = [‘22‘,‘33‘,‘44‘] job = [‘it‘,‘teacher‘,‘student‘] age.extend(job) #[‘22‘, ‘33‘, ‘44‘, ‘it‘, ‘teacher‘, ‘student‘] print(age) print(job)
2. 深copy 淺copy
#淺copy name = [‘0alex‘,‘1jack‘,[‘21root‘,‘22redhat‘],‘3snake‘] print(‘name>‘,name) name2 = name.copy() name[3] = ‘吖吖‘ print(‘name>‘,name) print(‘name2>‘,name2) name[2][0] = ‘答復‘ print(‘name>‘,name) print(‘name2>‘,name2)
#淺copy 和淺copy的區別 import copy name3 = [‘0alex‘,‘1jack‘,[‘21root‘,‘22redhat‘],‘3snake‘] name4 = copy.copy(name3) #name4只是復制了name3,name3改變,它也改變 name5 = copy.deepcopy(name3) #name5 重新開辟一塊內存地址,指針,name3改變,name5不改變 name3[2][0] = ‘答復‘ print(‘name4>‘,name4) print(‘name5>‘,name5)
#3種淺copy import copy person = [‘0jack‘,[‘10alex‘,‘11root‘]] person2 = copy.copy(person) person3 = person[:] person4 = list(person) print(person2,person3,person4)
2. 元組
#元組, 不可以修改 ‘‘‘ name = (‘jack‘,‘alex‘) name.append(‘root‘) AttributeError: ‘tuple‘ object has no attribute ‘append‘ ‘‘‘ name = (‘jack‘,‘alex‘) print(name.count(‘alex‘)) print(name.index(‘jack‘))
#聯合賬戶,共同存款 salary = 1000 count = [‘name‘,[‘saving‘,salary]] print(count) alex = count[:] wife = count[:] alex[0]=‘alex‘ wife[0]=‘wife‘ count[1][1]= salary+1000 print(alex) print(wife)
3.購物車程序
‘‘‘
程序練習
請閉眼寫出以下程序。
程序:購物車程序
需求:
1. 啟動程序後,讓用戶輸入工資,然後打印商品列表
2. 允許用戶根據商品編號購買商品
3. 用戶選擇商品後,檢測余額是否夠,夠就直接扣款,不夠就提醒
4. 可隨時退出,退出時,打印已購買商品和余額
‘‘‘
1 info = ‘‘‘ 2 ---------------- 3 4 Welcome to CBBC 5 6 ---------------- 7 ‘‘‘ 8 print(info) 9 10 11 salary = int(input(‘your salary > ‘).strip()) 12 shopping_list = [] 13 while True: 14 goods_list = [[‘air‘,‘10000‘],[‘apple‘,‘8888‘],[‘mi‘,‘3999‘],[‘coffee‘,‘23‘],[‘page‘,‘1‘]] 15 print(len(goods_list)) 16 for index,item in enumerate(goods_list): 17 print(index,item ) 18 19 20 choice = input(‘your choice [q:exit]> ‘).strip() 21 if choice.isnumeric() and 0 < int(choice) < len(goods_list): 22 choice = int(choice) 23 24 25 if int(goods_list[choice][1]) < salary : 26 salary -= int(goods_list[choice][1]) 27 shopping_list.append(goods_list[choice][0]) 28 print(salary) 29 print(shopping_list) 30 else: 31 print(‘余額不足‘) 32 33 elif choice == ‘q‘: 34 break 35 else: 36 print(‘請重新輸入‘) 37 38 39 info_bye = ‘‘‘ 40 --------------- 41 bye - bye 42 --------------- 43 your salary:%s 44 your goods:%s 45 ‘‘‘%(salary,shopping_list) 46 47 print(info_bye)View Code
#打印list的#下標,索引 #下標和索引 goods_list = [[‘air‘,‘10000‘],[‘apple‘,‘8888‘],[‘mi‘,‘3999‘],[‘coffee‘,‘23‘],[‘page‘,‘1‘]] #下標,索引 for index,item in enumerate(goods_list): print(index,item) #索引 for i in goods_list: print(i) #下標 for i in goods_list: print(goods_list.index(i))
#判斷是不是數字??? choice = input(‘>‘) if choice.isdigit(): print(‘ok‘) elif choice.isnumeric(): print(‘11‘)
#高亮顯示 print(‘this is a book‘) print(‘this is a \033[32;1m book \033[0m‘)
4.字符串str
name = ‘my name is \t alex‘ print(name.capitalize()) #My name is alex print(name.count(‘a‘)) #2 print(name.center(50,‘+‘)) #++++++++++++++++my name is alex+++++++++++++++++ print(name.endswith(‘ex‘)) #以ex結尾i 返回True print(name.expandtabs(30)) #\t 轉換成空格 print(name.find(‘name‘)) #3 print(name[name.find(‘name‘):9]) #切片 name[3:9)
#拼接 name2 = ‘my name is {name},age is {age}‘ print(name2.format(name=‘alex‘,age=‘22‘)) print(name2.format_map({‘name‘:‘jack‘,‘age‘:33}))
#判斷是否是什麽 print(name.isalnum()) #阿拉伯數字 print(‘123aa‘.isalnum()) print(‘adfaDFAS‘.isalpha()) print(‘233‘.isdecimal()) print(‘-44‘.isdigit()) #是否整數 print(‘ 9 44‘.isnumeric()) #是否只有數字 print(‘asf##‘.isdecimal()) print(‘My‘.istitle()) print(‘My‘.isprintable()) print(‘My‘.isupper())
#拼接 print(‘My name is ‘.join(‘==/+‘)) # = = / + print(‘+‘.join([‘1‘,‘3‘,‘4‘])) #1+3+4 print(‘aaaa‘.ljust(50,‘+‘)) print(‘aaaa‘.rjust(50,‘+‘)) print(‘aleEXSSnn‘.zfill(20)) #00000000000aleEXSSnn
#大小寫 print(‘SNAEKwe‘.lower()) #snaekwe print(‘SNAEKwe‘.upper()) #SNAEKWE print(‘aleEXSSnn‘.swapcase()) #ALEexssNN
#去除空格,換行 print(‘\talex\t‘.lstrip()) print(‘\talex\t‘.rstrip()) #alex # alex print(‘ \nalex\t‘.strip()) #alex
#替換 password = str.maketrans(‘abcde123‘,‘12345kdf‘) #abcde123 #12345kdf #alex??? #1l5x print(‘alex‘.translate(password)) print(‘alex‘.replace(‘l‘,"L")) print(‘alexl‘.replace(‘l‘,"L",1)) print(‘alex li‘.rfind(‘1‘)) print(‘aleEXSSnn‘.title()) #Aleexssnn
#split print(‘alex is LI‘.split()) #[‘alex‘, ‘is‘, ‘LI‘] print(‘alex is LI‘.split(‘l‘)) #[‘a‘, ‘ex is LI‘] print(‘1+2+4‘.split(‘+‘)) #[‘1‘, ‘2‘, ‘4‘] print(‘1+2\n+4‘.splitlines()) #[‘1+2‘, ‘+4‘] print(‘1+2\n+4‘.split()) #[‘1+2‘, ‘+4‘]
5.字典 dict
#初始化dict dic = dict.fromkeys([6,7,8]) print(dic) #{8: None, 6: None, 7: None} dic1 = dict.fromkeys([6,7,8],‘test‘) print(dic1) #{8: ‘test‘, 6: ‘test‘, 7: ‘test‘} dic2 = dict.fromkeys([6,7,8],[11,{‘alex‘:33},‘ssss‘]) print(dic2) #{8: [11, {‘alex‘: 33}, ‘ssss‘], 6: [11, {‘alex‘: 33}, ‘ssss‘], 7: [11, {‘alex‘: 33}, ‘ssss‘]}
info = { ‘name‘:‘alex‘, ‘age‘:‘23‘, ‘job‘:‘it‘, ‘sal‘:‘1111‘, } print(info) # k :v 無序的
#key value item print(info.keys()) print(info.values()) print(info.items()) # dict_keys([‘job‘, ‘name‘, ‘sal‘, ‘age‘]) # dict_values([‘it‘, ‘alex‘, ‘1111‘, ‘23‘]) # dict_items([(‘job‘, ‘it‘), (‘name‘, ‘alex‘), (‘sal‘, ‘1111‘), (‘age‘, ‘23‘)])
#查找 print(info.get(‘sss‘,None)) #print(info[‘sss‘]) #KeyError: ‘sss‘ print(‘23‘ in info)#False print(‘age‘ in info)#True
#改 增 info[‘age‘]=‘66‘ print(info) info[‘snake‘]=‘we‘ print(info)
#刪除 del info[‘age‘] print(info) info.pop(‘name‘) print(info)
#合並 兩個字典 b = { ‘stu‘:‘jack‘, ‘saving‘:‘2000‘, ‘course‘:‘python‘, } info.update(b) print(info) #{‘snake‘: ‘we‘, ‘sal‘: ‘1111‘, ‘stu‘: ‘jack‘, ‘course‘: ‘python‘, ‘saving‘: ‘2000‘, ‘job‘: ‘it‘}
#嵌套 三維字典 av_msg = { ‘we‘:{ ‘top‘:[‘957‘,‘v‘], ‘jug‘:[‘condi‘,‘mlxg‘], ‘mid‘:[‘xiye‘,‘xiaohu‘] }, ‘edg‘:{ ‘xia‘:[‘zet‘,‘zhao‘], ‘jug‘:[‘loli‘,‘clearlove‘], ‘top‘:[‘mouse‘,‘audi‘] }, ‘rng‘:{ ‘top‘:[‘letme‘,‘kornal‘], ‘xia‘:[‘y4‘,‘uzi‘], ‘fuzhu‘:[‘ming‘,‘ning‘] } } #修改 print(av_msg) av_msg[‘rng‘][‘top‘][0]=‘longlong‘ print(av_msg) #增加 av_msg.setdefault(‘ig‘,{‘top‘:[‘sky‘,‘skey‘]}) #增加一條 av_msg.setdefault(‘rng‘,{‘top‘:[‘sky‘,‘skey‘]}) #如果存在rng,則不添加 print(av_msg) #循環打印key for k in av_msg: print(k) #ig # edg # we # rng #循環打印value for v in av_msg: print(av_msg[v]) #字典轉換成列表,不推薦使用 for k,v in av_msg.items(): print(k,v) # for index,item in enumerate(av_msg) for index,item in enumerate(av_msg): print(index,item) # 0 rng # 1 ig # 2 we # 3 edg for index,item in enumerate(av_msg): print(index,item,av_msg[item]) #0 edg {‘xia‘: [‘zet‘, ‘zhao‘], ‘jug‘: [‘loli‘, ‘clearlove‘], ‘top‘: [‘mouse‘, ‘audi‘]} #1 ig {‘top‘: [‘sky‘, ‘skey‘]} #2 rng {‘top‘: [‘longlong‘, ‘kornal‘], ‘xia‘: [‘y4‘, ‘uzi‘], ‘fuzhu‘: [‘ming‘, ‘ning‘]} #3 we {‘mid‘: [‘xiye‘, ‘xiaohu‘], ‘top‘: [‘957‘, ‘v‘], ‘jug‘: [‘condi‘, ‘mlxg‘]}
作業三:多級菜單
三級菜單
可依次選擇進入各子菜單
所需新知識點:列表、字典
‘‘‘
info ={ ‘China‘:{ ‘陜西‘:{ ‘西安‘:[‘小寨‘,‘雁塔‘,‘高新‘], ‘鹹陽‘:[‘乾陵‘,‘昭陵‘,‘武陵‘], ‘渭南‘:[‘渭水‘,‘華山‘,‘黃河‘], }, ‘江蘇‘:{ ‘昆山‘:[‘統一‘,‘康師傅‘,‘三一‘], ‘上海‘:[‘機場‘,‘英語‘,‘明珠‘], ‘南京‘:[‘大橋‘,‘長江‘,‘漁船‘], }, ‘北京‘:{ ‘北京市‘:[‘長城‘,‘故宮‘,‘頤和園‘], ‘天津‘:[‘炮臺‘,‘海港‘,‘包子‘], ‘煙臺‘:[‘海灘‘,‘大海‘,‘海鮮‘], }, }, ‘USA‘:{‘埃塞爾州‘:{‘洛杉磯‘:[‘湖人‘,‘火箭‘,‘勇士‘]}}, ‘Europe‘:{‘萊茵河‘:{‘英國‘:[‘神奇女俠‘,‘希特勒‘,‘諾曼底‘]}} } while True: for item in info: print(item) choice_1 = input(‘choice_1 [q|.]>‘).strip() if choice_1 in info: while True: for i in info[choice_1]: print(‘\t‘,i) choice_2 = input(‘\tchoice_2 [q|e|.]>‘).strip() if choice_2 in info[choice_1]: while True: for i in info[choice_1][choice_2]: print(‘\t\t‘,i) choice_3 = input(‘\t\tchoice_3 [q|e|.]>‘).strip() if choice_3 in info[choice_1][choice_2]: while True: print(‘\t\t\t‘,info[choice_1][choice_2][choice_3]) choice_4 = input(‘this is bottom [ q | e]>‘) if choice_4 == ‘q‘: break elif choice_4 == ‘e‘: exit() elif choice_3 == ‘q‘: break elif choice_3 == ‘e‘: exit() elif choice_2 == ‘q‘: break elif choice_2 == ‘e‘: exit() elif choice_1 == ‘q‘: exit()View Code
‘‘‘ 如何獲取dict 下標對應的item ‘‘‘
python基礎篇 day2