python從零進階之路——day2
阿新 • • 發佈:2018-11-02
列表list:增,刪,查,改,切片,拷貝
1.切片
# -*- coding-utf8 -*- # author:zingerman name=['hu','zhao','wang','zhou'] print(name[:2]) #預設從0開始 print(name[-3:-1]) #不能寫成name[-1:-3] print(name[-3:]) #預設從0開始 print(name[::2]) #步長為2,等效與name[0:-1:2]
2.增:
# -*- coding-utf8 -*-# author:zingerman name=['hu','zhao','wang','zhou'] name.append('sun') #在列表的末尾新增元素 print(name) name.insert(1,'qian') #按索引插入元素 print(name) name1=[1,2,3] name.extend(name1) #extend() 函式用於在列表末尾一次性追加另一個序列中的多個值(用新列表擴充套件原來的列表) print(name)
3.刪:
# -*- coding-utf8 -*- # author:zingermanname=['hu','zhao','wang','zhou','qian'] name.remove('zhao') #remove() 函式用於移除列表中某個值,無返回值 print(name) del name[1] #根據索引刪除列表中的元素 print(name) name.pop(1) #預設刪除列表最後一個,或按索引刪除 print(name)
4.查,拷貝:
# -*- coding-utf8 -*- # author:zingerman importcopy name=['hu','zhao',['qian','sun'],'wang','zhou'] print(name[2]) print(name[2][1]) print(name.index("hu")) name2=copy.copy(name) #另外兩種copy的方式:1,name2=name[:] 2.name2=list(name) print(name2) #name[2]='b' name[2][1]='1' #1、copy.copy 淺拷貝 只拷貝父物件,不會拷貝物件的內部的子物件,拷貝的是內部子物件的地址,淺拷貝常用於建立聯合賬號 print(name) #2、copy.deepcopy 深拷貝 拷貝物件及其子物件 print(name2)
5.其他:
# -*- coding-utf8 -*- # author:zingerman name=['hu','zhao','wang','zhou'] name.reverse() print(name) name.sort() print(name) name.clear() print(name)
元組:
元組其實跟列表差不多,也是存一組數,只不是它一旦建立,便不能再修改,所以又叫只讀列表
語法
1 |
names
=
(
"alex"
,
"jack"
,
"eric"
)
|
它只有2個方法,一個是count,一個是index,完畢。
購物車作業 :
#!/usr/bin/env python # author:zingerman product_list = [ ('Iphone', 5800), ('Mac Pro', 9800), ('Bike', 800), ('Watch', 10600), ('Coffee', 31), ('Alex Python', 120), ] shopping_list = [] salary = input('輸入你的工資:') if salary.isdigit(): salary = int(salary) for item in product_list: print(product_list.index(item), item) coustom_choice = input('請輸入商品標號;') # print(type(coustom_choice)) while True: if coustom_choice.isdigit(): coustom_choice = int(coustom_choice) if coustom_choice < len(product_list) and coustom_choice >= 0: if product_list[coustom_choice][1] <= salary: # 買得起 shopping_list.append(product_list[coustom_choice]) salary -= product_list[coustom_choice][1] print('你已經購買了%s,你的賬戶還剩%s元' % (shopping_list, salary)) coustom_choice = input('請繼續輸入商品標號;') else: print('你的餘額不足,還剩%s元' % (salary)) break else: coustom_choice = input('你輸入編號太大,請重新輸入') elif coustom_choice == 'q': break else: coustom_choice = input('你輸入編號有誤,請重新輸入') print('謝謝惠顧,你已經購買了%s,你的賬戶還剩%s元' % (shopping_list, salary))
字串操作:
name.capitalize() 首字母大寫 name.casefold() 大寫全部變小寫 name.center(50,"-") 輸出 '---------------------Alex Li----------------------' name.count('lex') 統計 lex出現次數 name.encode() 將字串編碼成bytes格式 name.endswith("Li") 判斷字串是否以 Li結尾 "Alex\tLi".expandtabs(10) 輸出'Alex Li', 將\t轉換成多長的空格 name.find('A') 查詢A,找到返回其索引, 找不到返回-1 format : >>> msg = "my name is {}, and age is {}" >>> msg.format("alex",22) 'my name is alex, and age is 22' >>> msg = "my name is {1}, and age is {0}" >>> msg.format("alex",22) 'my name is 22, and age is alex' >>> msg = "my name is {name}, and age is {age}" >>> msg.format(age=22,name="ale") 'my name is ale, and age is 22' format_map >>> msg.format_map({'name':'alex','age':22}) 'my name is alex, and age is 22' msg.index('a') 返回a所在字串的索引 '9aA'.isalnum() True '9'.isdigit() 是否整數 name.isnumeric name.isprintable name.isspace name.istitle name.isupper "|".join(['alex','jack','rain']) 'alex|jack|rain' maketrans >>> intab = "aeiou" #This is the string having actual characters. >>> outtab = "12345" #This is the string having corresponding mapping character >>> trantab = str.maketrans(intab, outtab) >>> >>> str = "this is string example....wow!!!" >>> str.translate(trantab) 'th3s 3s str3ng 2x1mpl2....w4w!!!' msg.partition('is') 輸出 ('my name ', 'is', ' {name}, and age is {age}') >>> "alex li, chinese name is lijie".replace("li","LI",1) 'alex LI, chinese name is lijie' msg.swapcase 大小寫互換 >>> msg.zfill(40) '00000my name is {name}, and age is {age}' >>> n4.ljust(40,"-") 'Hello 2orld-----------------------------' >>> n4.rjust(40,"-") '-----------------------------Hello 2orld' >>> b="ddefdsdff_哈哈" >>> b.isidentifier() #檢測一段字串可否被當作標誌符,即是否符合變數命名規則 True
字典:
1.增,改:
# -*- coding-utf8 -*- # author:zingerman info = { '01': "hu", '02': "li", '03': "zhao", } info[4]='sun'
info['02']='wang'
print(info)
2.刪:
# -*- coding-utf8 -*- # author:zingerman info = {'01': "hu",'02': "li",'03': "zhao",'04':'wang'} info.pop('01') #標準刪除姿勢 del info['02'] #也是刪除 info.popitem() #隨機刪除 print(info)
3.找;
# -*- coding-utf8 -*- # author:zingerman info = {'01': "hu",'02': "li",'03': "zhao",'04':'wang'} print('01' in info) #標準查詢 print(info.get('01')) #獲取,可用於查詢,如果找不到,返回none print(info['01']) #查詢,但是找不到會報錯,建議用上一種
4.字典巢狀:
av_catalog = { "歐美":{ "www.youporn.com": ["很多免費的,世界最大的","質量一般"], "www.pornhub.com": ["很多免費的,也很大","質量比yourporn高點"], "letmedothistoyou.com": ["多是自拍,高質量圖片很多","資源不多,更新慢"], "x-art.com":["質量很高,真的很高","全部收費,屌比請繞過"] }, "日韓":{ "tokyo-hot":["質量怎樣不清楚,個人已經不喜歡日韓範了","聽說是收費的"] }, "大陸":{ "1024":["全部免費,真好,好人一生平安","伺服器在國外,慢"] } } av_catalog["大陸"]["1024"][1] += ",可以用爬蟲爬下來" print(av_catalog["大陸"]["1024"]) #ouput ['全部免費,真好,好人一生平安', '伺服器在國外,慢,可以用爬蟲爬下來']
5.其他用法:
# author:zingerman info = {'01': "hu",'02': "li",'03': "zhao",'04':'wang'} print(info.values()) print(info.keys()) print(info.setdefault(4,'sun') ,'\t\t\t',info) info1 ={'01': 'men',1:2} info.update(info1) print(info) #有則修改,無則新增 print("字典值 : %s" % info.items()) #items() 函式以列表返回可遍歷的(鍵, 值) 元組陣列 # 遍歷字典列表 for key, values in info.items():
print(key, values)