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

 更新时间:2022年02月23日 08:43:36   作者:简一林下之风  
这篇文章主要为大家详细介绍了Python的字典,元组,布尔类型和读写文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

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的re模块正则表达式操作

    Python的re模块正则表达式操作

    这篇文章主要介绍了Python的re模块正则表达式操作 的相关资料,需要的朋友可以参考下
    2016-05-05
  • 浅析Python如何监听和响应键盘按键

    浅析Python如何监听和响应键盘按键

    在许多编程场景中,接收并响应用户输入是至关重要的,本文主要为大家详细介绍如何使用Python来监听和响应键盘按键,有需要的小伙伴可以参考下
    2024-03-03
  • Python 实现try重新执行

    Python 实现try重新执行

    今天小编就为大家分享一篇Python 实现try重新执行,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • Python可视化学习之seaborn绘制线型回归曲线

    Python可视化学习之seaborn绘制线型回归曲线

    这篇文章主要为大家介绍了如何利用seaborn绘制变量之间线型回归(linear regression)曲线,2文中涉及如下两个重要函数:seaborn.regplot和seaborn.lmplot,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-02-02
  • 自动化测试Pytest单元测试框架的基本介绍

    自动化测试Pytest单元测试框架的基本介绍

    这篇文章主要介绍了Pytest单元测试框架的基本介绍,包含了Pytest的概念,Pytest特点,其安装流程步骤以及相关配置流程,有需要的朋友可以参考下
    2021-08-08
  • Python常用的数据清洗方法详解

    Python常用的数据清洗方法详解

    这篇文章主要介绍了Python常用的数据清洗方法,在数据处理的过程中,一般都需要进行数据的清洗工作,如数据集是否存在重复、是否存在缺失、数据是否具有完整性和一致性、数据中是否存在异常值等,需要的朋友可以参考下
    2023-07-07
  • Python Diagrams库以代码形式生成云系统架构图实例详解

    Python Diagrams库以代码形式生成云系统架构图实例详解

    这篇文章主要介绍了Python Diagrams库以代码形式生成云系统架构图实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01
  • 图文详解如何利用PyTorch实现图像识别

    图文详解如何利用PyTorch实现图像识别

    这篇文章主要给大家介绍了关于如何利用PyTorch实现图像识别的相关资料,文中通过图文以及实例代码介绍的非常详细,对大家学习或者使用PyTorch具有一定的参考学习价值,需要的朋友可以参考下
    2023-04-04
  • Python中的单例模式与反射机制详解

    Python中的单例模式与反射机制详解

    这篇文章主要为大家介绍了Python中的单例模式与反射机制,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • OpenCV半小时掌握基本操作之直方图

    OpenCV半小时掌握基本操作之直方图

    这篇文章主要介绍了OpenCV基本操作之直方图,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09

最新评论