Python学习笔记之字典,元组,布尔类型和读写文件

Flower ·
更新时间:2024-11-14
· 610 次阅读

目录

1.字典dict

1.1列表和字典的区别

1.2字典示例

1.3练习:写中国省份与省份缩写对应的字母代码

2.元组tuple

3.布尔类型bool

4.读写文件

4.1用命令做一个编辑器

4.2练习写类似的脚本

4.3用一个target.write()来打印line1、line2、line3

4.4Q&A

1.为什么我们需要给open多赋予一个’w’参数

2.如果你用w模式打开文件,那么你还需要target.truncate()吗

总结

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:\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()不是必须的。

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注软件开发网的更多内容! 



python学习 字典 布尔类型 元组 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号