首頁 > 軟體

Python學習筆記之字典,元組,布林型別和讀寫檔案

2022-02-23 10:01:05

1.字典dict

不同於列表只能用數位獲取資料,字典可以用任何東西來獲取,因為字典通過鍵索引值,而鍵可以是字串、數位、元組。

1.1 列表和字典的區別

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}

1.2 字典範例

# 建立一個州名和州的縮寫的對映
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 str

printMsg(“Hello world!”)

#在輸入字串時,需要帶引號

1.3 練習:寫中國省份與省份縮寫對應的字母程式碼

sx={
    "廣東":"粵",
    "福建":"閩",
    "江西":"贛",
    "安徽":"皖"
}

sx["雲南"]="滇"
sx["貴州"]="黔"
#定義函數,輸入省份,輸出省份縮寫

def suoxie(province):
    suoxie=sx.get(province)
    if not suoxie:
        print(f"對不起,我還沒在系統輸入{province}省的縮寫。")
    else:
        print(f"{province}省的縮寫是:{suoxie}")

suoxie("廣東")
suoxie("黑龍江")
廣東省的縮寫是:粵
對不起,我還沒在系統輸入黑龍江省的縮寫。

2.元組tuple

元組類似於列表,內部元素用逗號分隔。但是元組不能二次賦值,相當於唯讀列表。

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

3.布林型別bool

True and True  #與運算
1==1 and 1==2
1==1 or 2!=1  # 或運算,!=表示不等於
not (True and False)   # 非運算
not (1==1 and 0!=1)

4.讀寫檔案

close:關閉檔案

read:讀取檔案內容,可將讀取結果賦給另一個變數

readline:唯讀取文字檔案的一行內容

truncate:清空檔案

write(‘stuff’):給檔案寫入一些“東西”

seek(0):把讀/寫的位置移到檔案最開頭

4.1 用命令做一個編輯器

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.

用編輯器開啟建立的檔案,結果如下圖:

4.2 練習寫類似的指令碼

使用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

開啟檔案結果如下:

4.3 用一個target.write()來列印line1、line2、line3

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 表示要寫入檔案的字串

開啟結果如下:

4.4 Q&A

1.為什麼我們需要給open多賦予一個’w’引數

open()只有特別指定以後它才會進行寫入操作。

open() 的預設引數是open(file,‘r’) 也就是讀取文字的模式,預設引數可以不用填寫。

如果要寫入檔案,需要將引數設為寫入模式,因此需要用w引數。

2.如果你用w模式開啟檔案,那麼你還需要target.truncate()嗎

Python的open函數檔案中說:“It will be truncated when opened for writing.”,也就是說truncate()不是必須的。

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容! 


IT145.com E-mail:sddin#qq.com