# 一句話實(shí)現(xiàn)交換字典的key和value
dic1={'a':1,'b':2,'c':3}
gen3=((value,key) for key,value in dic1.items())
print(dict(gen3))
# dic1=dict(((value,key) for key,value in dic1.items()))
t=[[1,2],[2,3],[3,4]]
def dice1(sep):
p={}
for item in sep:
for item1 in range(2):
p[item[0]]=item[1]
return p
print(dice1(t))
(表達(dá)式 for 變量 in 序列 if 條件語(yǔ)句)
def gen():
for x in 序列:
if 條件語(yǔ)句:
yield 表達(dá)式
# python的三目運(yùn)算符
# C語(yǔ)言 條件語(yǔ)句?值1:值2
# 如果條件語(yǔ)句為真,整個(gè)表達(dá)式的值是值1,否則值2
python 中
值1 if 條件語(yǔ)句 else 值2
a,b=10,20
result = a if a>b else b
print(result)
數(shù)據(jù)持久化
程序中產(chǎn)生的數(shù)據(jù)默認(rèn)保存在內(nèi)存中 程序結(jié)束后數(shù)據(jù)自動(dòng)銷毀途蒋。如果需要程序運(yùn)行結(jié)束后數(shù)據(jù)不銷毀裳凸,就需要數(shù)據(jù)持久化 將數(shù)據(jù)保存到文件中,然后將文件保存在硬盤中
2.文件操作(對(duì)文件內(nèi)容操作)
1.打開(kāi)文件
open(file,mode='r',encoding=None) - 以指定的方式打開(kāi)文件翁都,返回文件對(duì)象
file - 文件路徑,可以寫絕對(duì)路徑也可以寫相對(duì)路徑
絕對(duì)路徑 - 文件的具體位置谅猾,完整路徑
相對(duì)路徑 - 需要將文件保存在當(dāng)前工程中
./ - 當(dāng)前目錄 (可以省略)
../ - 當(dāng)前目錄的上層目錄
.../ - 當(dāng)前目錄上層目錄的上層目錄
依次類推
x1=f.read() 報(bào)錯(cuò) 以'w'只寫的方式打開(kāi)柄慰,不能讀
x=f.read() # 讀所有
print(x)
x1=f.read()
print(x1) #第二次讀不出來(lái) 因?yàn)榈谝淮巫x到了最后
f.seek(0) 設(shè)置讀寫位置()里面填字節(jié)大小
f.readline()讀一行
如果讀取內(nèi)容到最后沒(méi)有了鳍悠,使用read/readline 會(huì)返回空字符串 讀一個(gè)本地的txt文件的內(nèi)容,一行一行的讀,度完為止
s=open('test',encoding='utf-8')
while True:
print(s.readline())
if s.readline()=='':
break
3.字節(jié)類型(bytes)
將其他類型轉(zhuǎn)換成bytes類型:整數(shù) 布爾 字符串(要加encoding='utf-8' 以'br'/'rb'的方式讀文件坐搔,也能拿到
兩種將字符串轉(zhuǎn)換成二進(jìn)制的方法
print(bytes('你好',encoding='utf-8'))
print('你好!'.encode())
兩種將bytes轉(zhuǎn)換成字符串的方法
b1='路飛'.encode()
print(b1)
str1=str(b1,encoding='utf-8')
print(str1)
str2=b1.decode(encoding='utf-8')
print(str2)
二進(jìn)制文件的讀寫
圖片藏研、視頻、音頻等都是二進(jìn)制文件概行。這些文件只能以
帶'b'的方式打開(kāi)然后操作
# 讀操作
# image_file=open('圖片.jpg','br')
# b1=image_file.read()
# 寫操作
image_file2=open('新圖片.jpg','wb')
image_file2.write(b1)
什么是json數(shù)據(jù)
滿足json格式要求的數(shù)據(jù)就是json數(shù)據(jù);文件內(nèi)容滿足json 格式要求蠢挡,就是json文件
import json #這個(gè)內(nèi)置的
json格式要求
1.一個(gè)json有且只有一個(gè)數(shù)據(jù)
2.這個(gè)數(shù)據(jù)必須是json支持的數(shù)據(jù)類型的數(shù)據(jù)
json支持的數(shù)據(jù)類型:
number(數(shù)字) - 包含所有的整數(shù),小數(shù),科學(xué)計(jì)數(shù)法 例如 3e4 10.23 12
string(字符串) - 使用(!!雙引號(hào)!!)的字符集
(bool)布爾 - 只有true false (小寫)
(array)數(shù)組 - 相當(dāng)于python中的列表
(dict)字典 - 鍵只能是字符串凳忙,值任何數(shù)據(jù)
null - None
# 2.python數(shù)據(jù)和json數(shù)據(jù)的相互轉(zhuǎn)換
# python中內(nèi)置json模塊业踏,用來(lái)支持json操作
json 轉(zhuǎn) python
json -> python
數(shù)字 int/float
字符串 str,有可能將"變?yōu)?
布爾 true變?yōu)門rue,false變?yōu)镕alse
數(shù)組 list
字典 dict
null None
json.loads(字符串,encoding='utf-8') - 將json數(shù)據(jù)轉(zhuǎn)換成python對(duì)應(yīng)的數(shù)據(jù)
注意:字符串要求字符串內(nèi)容必須是json數(shù)據(jù)(去掉引號(hào)之后是json數(shù)據(jù))
print(json.loads('"abc"'))
python -> json
int/float number
bool ture、false
str 加雙引號(hào)
list/tuple 數(shù)組[]
dict 字典
None null
# json.dumps(數(shù)據(jù)) - 將pytoon數(shù)據(jù)變成json數(shù)據(jù)
print(json.dumps(({2:2,3:3})))