<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
不同於列表只能用數位獲取資料,字典可以用任何東西來獲取,因為字典通過鍵索引值,而鍵可以是字串、數位、元組。
things=["a","b","c","d"] print(things[1]) #只能用數位索引列表中的元素 things[1]="z" #列表的替換 print(things[1]) things.remove("d") #列表中刪除元素 things
stuff={"name":"zed","age":39,"height":6*12+2} print(stuff["name"]) #字典可用鍵索引值,鍵可以是字串、也可以是數位 print(stuff["age"]) print(stuff["height"]) stuff["city"]="xiamen" #字典中增加元素 stuff[1]="reading" #鍵為數位 print(stuff["city"]) print(stuff[1]) del stuff[1] #字典中刪除元素 del stuff["city"] stuff
zed 39 74 xiamen reading {'name': 'zed', 'age': 39, 'height': 74}
# 建立一個州名和州的縮寫的對映 states={ "oregon":"or", "florida":"fl", "california":"ca", "newyork":"ny", "michigan":"mi" } # 建立州的縮寫和對應州的城市的對映 cities={ "ca":"san francisco", "mi":"detroit", "fl":"jacksonville" } #新增城市 cities["ny"]="new york" cities["or"]="portland" # 輸出州的縮寫 print("-"*10) print("michigan's abbreviation is:",states["michigan"]) #個別州的縮寫 print("florida's abbreviation is:",states["florida"]) print("-"*10) for state,abbrev in list(states.items()): #所有州的縮寫,語法解釋見下方註釋1 print(f"{state} is abbreviated {abbrev}.") # 輸出州對應的城市 print("-"*10) print("florida has:",cities[states["florida"]]) #個別州對應的城市 print("-"*10) for abbrev,city in list(cities.items()): # 所有州的縮寫 print(f"{abbrev} has city {city}.") #同時輸出州的縮寫和州對應的城市 print("-"*10) for state,abbrev in list(states.items()): print(f"{state} state is abbreviated {abbrev}, and has city {cities[abbrev]}.") print("-"*10) def abbrev(state): #註釋4,定義函數,輸入州名,輸出州名的簡寫 abbrev=states.get(state) if not abbrev: #註釋3 print(f"sorry,it's {abbrev}.") else: print(f"{state} state is abbreviated {abbrev}.") abbrev("florida") abbrev("texas") print("-"*10,"method 1") city=cities.get("TX","Doesn't exist") print(f"the city for the state 'TX' is:{city}.") #注意'TX'需用單引號 print("-"*10,"method 2") #定義函數,輸入州名,輸出州所在的城市 def city(state): city=cities.get(states.get(state)) if not city: print(f"sorry,doesn't exist.") else: print(f"the city for the state {state} is:{city}.") city("texas") city("florida")
---------- michigan's abbreviation is: mi florida's abbreviation is: fl ---------- oregon is abbreviated or. florida is abbreviated fl. california is abbreviated ca. newyork is abbreviated ny. michigan is abbreviated mi. ---------- florida has: jacksonville ---------- ca has city san francisco. mi has city detroit. fl has city jacksonville. ny has city new york. or has city portland. ---------- oregon state is abbreviated or, and has city portland. florida state is abbreviated fl, and has city jacksonville. california state is abbreviated ca, and has city san francisco. newyork state is abbreviated ny, and has city new york. michigan state is abbreviated mi, and has city detroit. ---------- florida state is abbreviated fl. sorry,it's None. ---------- method 1 the city for the state 'TX' is:Doesn't exist. ---------- method 2 sorry,doesn't exist. the city for the state florida is:jacksonville.
註釋1
Python 字典 items() 方法以列表返回檢視物件,是一個可遍歷的key/value 對。
dict.keys()、dict.values() 和 dict.items() 返回的都是檢視物件( view objects),提供了字典實體的動態檢視,這就意味著字典改變,檢視也會跟著變化。
檢視物件不是列表,不支援索引,可以使用 list() 來轉換為列表。
我們不能對檢視物件進行任何的修改,因為字典的檢視物件都是唯讀的。
註釋2
字典 (Dictionary)get()函數返回指定鍵的值,如果值不在字典中,返回預設值。
語法:dict.get(key, default=None),引數 key–字典中要查詢的鍵,default – 如果指定鍵的值不存在時,返回該預設值。
註釋3
if not 判斷是否為NONE,程式碼中經常會有判斷變數是否為NONE的情況,主要有三種寫法:
第一種: if x is None(最清晰)
第二種: if not x
第三種: if not x is None
註釋4 將字串值傳遞給函數
def printMsg(str):
#printing the parameter
print strprintMsg(“Hello world!”)
#在輸入字串時,需要帶引號
sx={ "廣東":"粵", "福建":"閩", "江西":"贛", "安徽":"皖" } sx["雲南"]="滇" sx["貴州"]="黔"
#定義函數,輸入省份,輸出省份縮寫 def suoxie(province): suoxie=sx.get(province) if not suoxie: print(f"對不起,我還沒在系統輸入{province}省的縮寫。") else: print(f"{province}省的縮寫是:{suoxie}") suoxie("廣東") suoxie("黑龍江")
廣東省的縮寫是:粵 對不起,我還沒在系統輸入黑龍江省的縮寫。
元組類似於列表,內部元素用逗號分隔。但是元組不能二次賦值,相當於唯讀列表。
tuple=('runoob',786,2.23,'john',70.2) tinytuple=(123,'john') print(tuple[1:3]) #和list類似 print(tuple*2) print(tuple+tinytuple)
(786, 2.23) ('runoob', 786, 2.23, 'john', 70.2, 'runoob', 786, 2.23, 'john', 70.2) ('runoob', 786, 2.23, 'john', 70.2, 123, 'john')
元組是不允許更新的:
tuple=('runoob',786,2.23,'john',70.2) tuple[2]=1000 print(tuple)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-ae7d4b682735> in <module> 1 tuple=('runoob',786,2.23,'john',70.2) ----> 2 tuple[2]=1000 3 print(tuple) TypeError: 'tuple' object does not support item assignment
True and True #與運算
1==1 and 1==2
1==1 or 2!=1 # 或運算,!=表示不等於
not (True and False) # 非運算
not (1==1 and 0!=1)
close
:關閉檔案
read
:讀取檔案內容,可將讀取結果賦給另一個變數
readline
:唯讀取文字檔案的一行內容
truncate
:清空檔案
write(‘stuff’)
:給檔案寫入一些“東西”
seek(0)
:把讀/寫的位置移到檔案最開頭
from sys import argv #引入sys的部分模組argv(引數變數) filename = "C:\Users\janline\Desktop\test\euler笨辦法學python" #給自己新建的檔案命名,注意檔案地址要補雙槓 print(f"we're going to erase {filename}.") #格式化變數filename,並列印出來 print("if you don't want that, hit ctrl-c(^c).") print("if you do want, hit return. ") input("?") # 輸出"?",並出現輸入框 print("opening the file...") target=open(filename,'w') # w表示以寫的模式開啟,r表示以讀的模式開啟,a表示增補模式,w+表示以讀和寫的方式開啟,open(filename)預設唯讀 print("truncating the file. Goodbye!") target.truncate() #在變數target後面呼叫truncate函數(清空檔案) print("now I'm going to ask you for three lines.") line1=input("line 1: ") #輸出"line1:",接收輸入內容並存入變數line1中 line2=input("line 2: ") line3=input("line 3: ") print("I'm going to write these to the file.") target.write(line1) ##在變數target後面呼叫write函數,寫入變數line1中的內容,注意寫入的內容需是英文 target.write("n") # n換行 target.write(line2) target.write("n") target.write(line3) target.write("n") print("and finally, we close it.") target.close() #在變數target後面呼叫close函數,關閉檔案
we're going to erase C:UsersjanlineDesktoptesteuler笨辦法學python. if you don't want that, hit ctrl-c(^c). if you do want, hit return. ?return opening the file... truncating the file. Goodbye! now I'm going to ask you for three lines. line 1: address name should be double slacked line 2: see clearly for what problem happened line 3: look for answers by searching I'm going to write these to the file. and finally, we close it.
用編輯器開啟建立的檔案,結果如下圖:
使用read和argv來讀取建立的檔案:
filename="C:\Users\janline\Desktop\test\笨辦法學python\test.txt" txt=open(filename,'w+') print("Let's read the file") print("Let's write the file") line1=input("line1: ") line2=input("line2: ") print("Let's write these in the file") print("n") txt.write(line1) txt.write("n") txt.write(line2) txt.write("n") print(txt.read()) txt.close()
Let's read the file Let's write the file line1: read and write file are complicated line2: come on, it's been finished! Let's write these in the file
開啟檔案結果如下:
from sys import argv #引入sys的部分模組argv(引數變數) filename = "C:\Users\janline\Desktop\test\euler笨辦法學python" #給自己新建的檔案命名,注意檔案地址要補雙槓 print(f"we're going to erase {filename}.") #格式化變數filename,並列印出來 print("if you don't want that, hit ctrl-c(^c).") print("if you do want, hit return. ") input("?") # 輸出"?",並出現輸入框 print("opening the file...") target=open(filename,'w') # w表示以寫的模式開啟,r表示以讀的模式開啟,a表示增補模式,w+表示以讀和寫的方式開啟,open(filename)預設唯讀 print("truncating the file. Goodbye!") target.truncate() #在變數target後面呼叫truncate函數(清空檔案) print("now I'm going to ask you for three lines.") line1=input("line 1: ") #輸出"line1:",接收輸入內容並存入變數line1中 line2=input("line 2: ") line3=input("line 3: ") print("I'm going to write these to the file.") target.write(line1+"n"+line2+"n"+line3+"n") #見註釋 print("and finally, we close it.") target.close() #在變數target後面呼叫close函數,關閉檔案
we're going to erase C:UsersjanlineDesktoptesteuler笨辦法學python. if you don't want that, hit ctrl-c(^c). if you do want, hit return. ?return opening the file... truncating the file. Goodbye! now I'm going to ask you for three lines. line 1: 1 line 2: 2 line 3: 3 I'm going to write these to the file. and finally, we close it.
註釋
Python 中的檔案物件提供了 write() 函數,可以向檔案中寫入指定內容。該函數的語法格式:file.write(string)。其中,file 表示已經開啟的檔案物件;string 表示要寫入檔案的字串
開啟結果如下:
open()只有特別指定以後它才會進行寫入操作。
open() 的預設引數是open(file,‘r’) 也就是讀取文字的模式,預設引數可以不用填寫。
如果要寫入檔案,需要將引數設為寫入模式,因此需要用w引數。
Python的open函數檔案中說:“It will be truncated when opened for writing.”,也就是說truncate()不是必須的。
本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45