日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python學習筆記之字典,元組,布爾類型和讀寫文件_python

作者:簡一林下之風 ? 更新時間: 2022-04-27 編程語言

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)

 in 
      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:\Users\janline\Desktop\test\euler笨辦法學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:\Users\janline\Desktop\test\euler笨辦法學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()不是必須的。

總結

原文鏈接:https://blog.csdn.net/weixin_44729700/article/details/123050546

欄目分類
最近更新