標籤:而不是 表示 dmi 增刪改 代碼 數組 filename -- 比較
儲存大量資料的容器在Python中就叫做內建資料結構 Python中有四種資料結構: 列表,字典,元組(數組),集合 列表:list=[val1,val2,val3,val4] 字典:dict={key1:val1,key2:val2} 元組:tuple=(val1,val2,val3,val4) 集合:set={val1,val2,val3,val4} 關於一些方法什麼到處可以搜到,我就根據自己最近使用的一些經驗分享一下首先就是列表比較佔用記憶體,但是可以增刪改查,當是需要做一個常量的集合的時候就一定要記得用元組,還有就是字典很明顯就很人性化,當你需要知道自己怎麼去查一些資料的時候,而不是通過數字0,1,2,3去查的話就可以用這個,集合一般會用於去掉一些重複的資料,用set()一下就可以了,這就讓我想起我做過的一個小項目,就是很多網站都需要隨機產生一些假的使用者資料,但是我從搜狗詞庫裡面下載的又帶拼音又帶全名,我想要一個姓和名都分開的檔案,然後就自己寫了一段代碼分開了,先將這個分享一下吧,哈哈#coding:utf-8with open("C:/Users/Administrator/Desktop/Python練習資料/studentName.txt") as text:file=text.read().split()print(file)i=0content=""for name in file:i = i + 1if i%2==0: content+=name+"\n"with open("C:/Users/Administrator/Desktop/Python練習資料/fullName.txt", "w") as fileName:fileName.write(content)fileName.close()text.close() with open("C:/Users/Administrator/Desktop/Python練習資料/fullName.txt", "r") as fileName1:fileContent=fileName1.read().split("\n")print(fileContent)j = 0firstName=[]lastName=[] for fc in fileContent:listEv=list(fc)str = "" for fc1 in listEv:if len(listEv) == 3:j=j+1if j==3:j=0if j==1:firstName.append(fc1)else: str+=fc1if j==0:lastName.append(str)else: j=j+1if j==2:j=0if j==1:firstName.append(fc1)else:lastName.append(fc1)fN=set(firstName)lN=set(lastName)print(fN)print(lN)si=""for i in fN:si+=i+"\n"li = ""for i in lN:li += i+"\n"fileName1.close()with open("C:/Users/Administrator/Desktop/Python練習資料/firstName.txt", "w") as fF1:fF1.write(si) fF1.close()with open("C:/Users/Administrator/Desktop/Python練習資料/lastName.txt", "w") as lF1:lF1.write(li)lF1.close() 之前忘記考慮兩個字的名字了,還有就是要記得文字的長度可以用len(str)來擷取count()是表示子字串在字串中出現的次數,也就是比如str="this is a good thing"number=str.count(‘i‘,4,20)-----返回2,因為從4開始到20number=str.count(‘i‘)------這個時候就會是返回3
Python資料結構