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()):
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):
abbrev=states.get(state)
if not abbrev:
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}.")
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])
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
filename = "C:\\Users\\janline\\Desktop\\test\\euler笨办法学python"
print(f"we're going to erase {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')
print("truncating the file. Goodbye!")
target.truncate()
print("now I'm going to ask you for three lines.")
line1=input("line 1: ")
line2=input("line 2: ")
line3=input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("and finally, we close it.")
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
filename = "C:\\Users\\janline\\Desktop\\test\\euler笨办法学python"
print(f"we're going to erase {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')
print("truncating the file. Goodbye!")
target.truncate()
print("now I'm going to ask you for three lines.")
line1=input("line 1: ")
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()
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()不是必须的。
|