最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

1.字典dict

不同于列表只能用數(shù)字獲取數(shù)據(jù),字典可以用任何東西來獲取,因為字典通過鍵索引值,而鍵可以是字符串、數(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)建一個州名和州的縮寫的映射
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"])  #個別州的縮寫
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"]])  #個別州對應(yīng)的城市

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

#同時輸出州的縮寫和州對應(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'需用單引號

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() 方法以列表返回視圖對象,是一個可遍歷的key/value 對。

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

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

我們不能對視圖對象進(jìn)行任何的修改,因為字典的視圖對象都是只讀的。

注釋2

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

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

注釋3

if not 判斷是否為NONE,代碼中經(jīng)常會有判斷變量是否為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!”)

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

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)部元素用逗號分隔。但是元組不能二次賦值,相當(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  #與運算
1==1 and 1==2
1==1 or 2!=1  # 或運算,!=表示不等于
not (True and False)   # 非運算
not (1==1 and 0!=1)

4.讀寫文件

close:關(guān)閉文件

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

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

truncate:清空文件

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

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

4.1 用命令做一個編輯器

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

filename = "C:\\Users\\janline\\Desktop\\test\\euler笨辦法學(xué)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("?")  # 輸出"?",并出現(xiàn)輸入框

print("opening the file...")
target=open(filename,'w')   # w表示以寫的模式打開,r表示以讀的模式打開,a表示增補模式,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 用一個target.write()來打印line1、line2、line3

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

filename = "C:\\Users\\janline\\Desktop\\test\\euler笨辦法學(xué)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("?")  # 輸出"?",并出現(xiàn)輸入框

print("opening the file...")
target=open(filename,'w')   # w表示以寫的模式打開,r表示以讀的模式打開,a表示增補模式,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多賦予一個’w’參數(shù)

open()只有特別指定以后它才會進(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)文章

  • Python的re模塊正則表達(dá)式操作

    Python的re模塊正則表達(dá)式操作

    這篇文章主要介紹了Python的re模塊正則表達(dá)式操作 的相關(guān)資料,需要的朋友可以參考下
    2016-05-05
  • 淺析Python如何監(jiān)聽和響應(yīng)鍵盤按鍵

    淺析Python如何監(jiān)聽和響應(yīng)鍵盤按鍵

    在許多編程場景中,接收并響應(yīng)用戶輸入是至關(guān)重要的,本文主要為大家詳細(xì)介紹如何使用Python來監(jiān)聽和響應(yīng)鍵盤按鍵,有需要的小伙伴可以參考下
    2024-03-03
  • Python 實現(xiàn)try重新執(zhí)行

    Python 實現(xiàn)try重新執(zhí)行

    今天小編就為大家分享一篇Python 實現(xiàn)try重新執(zhí)行,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • Python可視化學(xué)習(xí)之seaborn繪制線型回歸曲線

    Python可視化學(xué)習(xí)之seaborn繪制線型回歸曲線

    這篇文章主要為大家介紹了如何利用seaborn繪制變量之間線型回歸(linear regression)曲線,2文中涉及如下兩個重要函數(shù):seaborn.regplot和seaborn.lmplot,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-02-02
  • 自動化測試Pytest單元測試框架的基本介紹

    自動化測試Pytest單元測試框架的基本介紹

    這篇文章主要介紹了Pytest單元測試框架的基本介紹,包含了Pytest的概念,Pytest特點,其安裝流程步驟以及相關(guān)配置流程,有需要的朋友可以參考下
    2021-08-08
  • Python常用的數(shù)據(jù)清洗方法詳解

    Python常用的數(shù)據(jù)清洗方法詳解

    這篇文章主要介紹了Python常用的數(shù)據(jù)清洗方法,在數(shù)據(jù)處理的過程中,一般都需要進(jìn)行數(shù)據(jù)的清洗工作,如數(shù)據(jù)集是否存在重復(fù)、是否存在缺失、數(shù)據(jù)是否具有完整性和一致性、數(shù)據(jù)中是否存在異常值等,需要的朋友可以參考下
    2023-07-07
  • Python Diagrams庫以代碼形式生成云系統(tǒng)架構(gòu)圖實例詳解

    Python Diagrams庫以代碼形式生成云系統(tǒng)架構(gòu)圖實例詳解

    這篇文章主要介紹了Python Diagrams庫以代碼形式生成云系統(tǒng)架構(gòu)圖實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • 圖文詳解如何利用PyTorch實現(xiàn)圖像識別

    圖文詳解如何利用PyTorch實現(xiàn)圖像識別

    這篇文章主要給大家介紹了關(guān)于如何利用PyTorch實現(xiàn)圖像識別的相關(guān)資料,文中通過圖文以及實例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用PyTorch具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2023-04-04
  • Python中的單例模式與反射機制詳解

    Python中的單例模式與反射機制詳解

    這篇文章主要為大家介紹了Python中的單例模式與反射機制,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11
  • OpenCV半小時掌握基本操作之直方圖

    OpenCV半小時掌握基本操作之直方圖

    這篇文章主要介紹了OpenCV基本操作之直方圖,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09

最新評論

正阳县| 富阳市| 双柏县| 汨罗市| 敦煌市| 桐梓县| 柘城县| 吉水县| 扎兰屯市| 舞钢市| 霍林郭勒市| 兴山县| 白沙| 康平县| 水城县| 伊春市| 青河县| 鹿泉市| 孝昌县| 安吉县| 霞浦县| 即墨市| 大荔县| 治县。| 金溪县| 云和县| 高密市| 舞钢市| 黑河市| 凤山市| 车致| 赤城县| 威信县| 囊谦县| 开阳县| 张家港市| 宕昌县| 开封市| 忻城县| 拜泉县| 长沙县|