欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python學(xué)習(xí)筆記之字典,元組,布爾類型和讀寫文件

 更新時(shí)間:2022年02月23日 08:43:36   作者:簡一林下之風(fēng)  
這篇文章主要為大家詳細(xì)介紹了Python的字典,元組,布爾類型和讀寫文件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

1.字典dict

不同于列表只能用數(shù)字獲取數(shù)據(jù),字典可以用任何東西來獲取,因?yàn)樽值渫ㄟ^鍵索引值,而鍵可以是字符串、數(shù)字、元組。

1.1 列表和字典的區(qū)別

things=["a","b","c","d"]   
print(things[1])   #只能用數(shù)字索引列表中的元素

things[1]="z"   #列表的替換
print(things[1])

things.remove("d")   #列表中刪除元素

things
stuff={"name":"zed","age":39,"height":6*12+2}
print(stuff["name"])   #字典可用鍵索引值,鍵可以是字符串、也可以是數(shù)字
print(stuff["age"])
print(stuff["height"])

stuff["city"]="xiamen"  #字典中增加元素
stuff[1]="reading"      #鍵為數(shù)字
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 字典示例

# 創(chuàng)建一個(gè)州名和州的縮寫的映射
states={
    "oregon":"or",
    "florida":"fl",
    "california":"ca",
    "newyork":"ny",
    "michigan":"mi"
}

# 創(chuàng)建州的縮寫和對應(yīng)州的城市的映射
cities={
    "ca":"san francisco",
    "mi":"detroit",
    "fl":"jacksonville"
}

#添加城市
cities["ny"]="new york"
cities["or"]="portland"

# 輸出州的縮寫
print("-"*10)
print("michigan's abbreviation is:",states["michigan"])  #個(gè)別州的縮寫
print("florida's abbreviation is:",states["florida"])

print("-"*10)
for state,abbrev in list(states.items()):  #所有州的縮寫,語法解釋見下方注釋1
    print(f"{state} is abbreviated {abbrev}.")

# 輸出州對應(yīng)的城市
print("-"*10)
print("florida has:",cities[states["florida"]])  #個(gè)別州對應(yīng)的城市

print("-"*10)
for abbrev,city in list(cities.items()): # 所有州的縮寫
    print(f"{abbrev} has city {city}.")

#同時(shí)輸出州的縮寫和州對應(yīng)的城市
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,定義函數(shù),輸入州名,輸出州名的簡寫
    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'需用單引號(hào)

print("-"*10,"method 2")  #定義函數(shù),輸入州名,輸出州所在的城市
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() 方法以列表返回視圖對象,是一個(gè)可遍歷的key/value 對。

dict.keys()、dict.values() 和 dict.items() 返回的都是視圖對象( view objects),提供了字典實(shí)體的動(dòng)態(tài)視圖,這就意味著字典改變,視圖也會(huì)跟著變化。

視圖對象不是列表,不支持索引,可以使用 list() 來轉(zhuǎn)換為列表。

我們不能對視圖對象進(jìn)行任何的修改,因?yàn)樽值涞囊晥D對象都是只讀的。

注釋2

字典 (Dictionary)get()函數(shù)返回指定鍵的值,如果值不在字典中,返回默認(rèn)值。

語法:dict.get(key, default=None),參數(shù) key–字典中要查找的鍵,default – 如果指定鍵的值不存在時(shí),返回該默認(rèn)值。

注釋3

if not 判斷是否為NONE,代碼中經(jīng)常會(huì)有判斷變量是否為NONE的情況,主要有三種寫法:

第一種: if x is None(最清晰)

第二種: if not x

第三種: if not x is None

注釋4 將字符串值傳遞給函數(shù)

def printMsg(str):
#printing the parameter
print str

printMsg(“Hello world!”)

#在輸入字符串時(shí),需要帶引號(hào)

1.3 練習(xí):寫中國省份與省份縮寫對應(yīng)的字母代碼

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

sx["云南"]="滇"
sx["貴州"]="黔"
#定義函數(shù),輸入省份,輸出省份縮寫

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

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

2.元組tuple

元組類似于列表,內(nèi)部元素用逗號(hào)分隔。但是元組不能二次賦值,相當(dāng)于只讀列表。

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  #與運(yùn)算
1==1 and 1==2
1==1 or 2!=1  # 或運(yùn)算,!=表示不等于
not (True and False)   # 非運(yùn)算
not (1==1 and 0!=1)

4.讀寫文件

close:關(guān)閉文件

read:讀取文件內(nèi)容,可將讀取結(jié)果賦給另一個(gè)變量

readline:只讀取文本文件的一行內(nèi)容

truncate:清空文件

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

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

4.1 用命令做一個(gè)編輯器

from sys import argv  #引入sys的部分模塊argv(參數(shù)變量)

filename = "C:\\Users\\janline\\Desktop\\test\\euler笨辦法學(xué)python"   #給自己新建的文件命名,注意文件地址要補(bǔ)雙杠

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("?")  # 輸出"?",并出現(xiàn)輸入框

print("opening the file...")
target=open(filename,'w')   # w表示以寫的模式打開,r表示以讀的模式打開,a表示增補(bǔ)模式,w+表示以讀和寫的方式打開,open(filename)默認(rèn)只讀

print("truncating the file. Goodbye!")
target.truncate()   #在變量target后面調(diào)用truncate函數(shù)(清空文件)

print("now I'm going to ask you for three lines.")

line1=input("line 1: ")   #輸出"line1:",接收輸入內(nèi)容并存入變量line1中
line2=input("line 2: ")
line3=input("line 3: ") 

print("I'm going to write these to the file.")

target.write(line1)   ##在變量target后面調(diào)用write函數(shù),寫入變量line1中的內(nèi)容,注意寫入的內(nèi)容需是英文
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后面調(diào)用close函數(shù),關(guān)閉文件
we're going to erase C:\Users\janline\Desktop\test\euler笨辦法學(xué)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.

用編輯器打開創(chuàng)建的文件,結(jié)果如下圖:

在這里插入圖片描述

4.2 練習(xí)寫類似的腳本

使用read和argv來讀取創(chuàng)建的文件:

filename="C:\\Users\\janline\\Desktop\\test\\笨辦法學(xué)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

打開文件結(jié)果如下:

在這里插入圖片描述

4.3 用一個(gè)target.write()來打印line1、line2、line3

from sys import argv  #引入sys的部分模塊argv(參數(shù)變量)

filename = "C:\\Users\\janline\\Desktop\\test\\euler笨辦法學(xué)python"   #給自己新建的文件命名,注意文件地址要補(bǔ)雙杠

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("?")  # 輸出"?",并出現(xiàn)輸入框

print("opening the file...")
target=open(filename,'w')   # w表示以寫的模式打開,r表示以讀的模式打開,a表示增補(bǔ)模式,w+表示以讀和寫的方式打開,open(filename)默認(rèn)只讀

print("truncating the file. Goodbye!")
target.truncate()   #在變量target后面調(diào)用truncate函數(shù)(清空文件)

print("now I'm going to ask you for three lines.")

line1=input("line 1: ")   #輸出"line1:",接收輸入內(nèi)容并存入變量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后面調(diào)用close函數(shù),關(guān)閉文件
we're going to erase C:\Users\janline\Desktop\test\euler笨辦法學(xué)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() 函數(shù),可以向文件中寫入指定內(nèi)容。該函數(shù)的語法格式:file.write(string)。其中,file 表示已經(jīng)打開的文件對象;string 表示要寫入文件的字符串

打開結(jié)果如下:

在這里插入圖片描述

4.4 Q&A

1.為什么我們需要給open多賦予一個(gè)’w’參數(shù)

open()只有特別指定以后它才會(huì)進(jìn)行寫入操作。

open() 的默認(rèn)參數(shù)是open(file,‘r’) 也就是讀取文本的模式,默認(rèn)參數(shù)可以不用填寫。

如果要寫入文件,需要將參數(shù)設(shè)為寫入模式,因此需要用w參數(shù)。

2.如果你用w模式打開文件,那么你還需要target.truncate()嗎

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

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容! 

相關(guān)文章

最新評論