Python自動化四--json模塊使用,集合操作,函數
阿新 • • 發佈:2018-06-15
lis sub 交集 pda script lose uno 程序 oat
內容:
- json模塊
- 集合操作
- 函數
一,json模塊
JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式。它基於ECMAScript的一個子集。
Python3 中可以使用 json 模塊來對 JSON 數據進行編解碼,它包含了兩個函數:
- json.dump(): 對數據進行編碼。
- json.load(): 對數據進行解碼。
json格式存儲--小例子
import json stu_info = { ‘laowang‘:{ ‘cars‘:[‘BMW‘,‘Ben-z‘] } } stu_str = json.dumps(stu_info) #把字典轉成json(字符串) print(‘json....‘,type(stu_str)) fw = open(‘stu.txt‘,‘w‘,encoding=‘utf-8‘) fw.write(stu_str) fw.close() fw = open(‘stu.json‘,‘w‘,encoding=‘utf-8‘) json.dump(stu_info,fw,indent=4) #自動寫入字典,存為json格式,單引號自動變為雙引號 #存在文件中的json格式為: { "laowang":{ "cars":["BMW","Ben-z"] } }
JSON編碼的字符串轉換回一個Python數據結構
import json # Python 字典類型轉換為 JSON 對象 data1 = { ‘no‘ : 1, ‘name‘ : ‘Runoob‘, ‘url‘ : ‘http://www.runoob.com‘ } json_str = json.dumps(data1) print ("Python 原始數據:", repr(data1)) print ("JSON 對象:", json_str) # 將 JSON 對象轉換為 Python 字典 data2 = json.loads(json_str) print ("data2[‘name‘]: ", data2[‘name‘]) print ("data2[‘url‘]: ", data2[‘url‘])
處理json格式文件
# 讀取數據,以UTF-8格式讀取文件為中文格式
with open(‘data.json‘, ‘r‘,encoding=‘utf-8) as f:
data = json.load(f)
# 寫入JSON 數據
with open(‘data.json‘, ‘w‘,encoding=‘utf-8) as f:
json.dump(data, f,ensure_ascii=False)#避免存入文件中的中文被轉為ascii碼
json存儲用戶密碼註冊文件--小例子
import json f = open(‘users.txt‘,‘a+‘,encoding=‘utf-8‘) #文件句柄,文件對象 f.seek(0) all_users = json.load(f) for i in range(3): u = input(‘user:‘).strip() p = input(‘p:‘).strip() cp = input(‘cp:‘).strip() if not u or not p: print(‘賬號、密碼不能為空‘) elif u in all_users: print(‘該用戶已經被註冊!‘) elif u not in all_users and cp==p: all_users[u]=p break f.seek(0) f.truncate() json.dump(all_users,f,indent=4) f.close()
二,集合操作
集合(set)是一個無序不重復元素的序列。
基本功能是進行成員關系測試和刪除重復元素。
可以使用大括號 { } 或者 set() 函數創建集合,註意:創建一個空集合必須用 set() 而不是 { },因為 { } 是用來創建一個空字典。
創建格式:
parame = {value01,value02,...}
#或者
set(value)
進行集合運算:
list = [1,2,3,4,5,3,6}
list_2 =[2,3,5,7,8]
list=set(list)
list_2 = set(list_2)
print(list.intersection(list_2),‘交集 ‘) #交集 取出重復數據
print(list.union(list_2),‘並集‘) # 並集 去重-統一展示
print(list.difference(list_2),‘差集‘) #差集-取出list中有 list_2 沒有
list_3 = set([1,3,6])
print(list_3.issubset(list)) #子集 list_3 的值在list 全有
print(list.issuperset(list_3)) #父集
print(list.symmetric_difference(list_2)) # 對稱差集 lsit 和 list_3 互相沒有的
a=set(a)
b=set(b)
print(a - b) # a和b的差集
print(a | b) # a和b的並集
print(a & b) # a和b的交集
print(a ^ b) # a和b中不同時存在的元素
集合操作:
list=set(list)
list.add(777) #一次添加一個
list.update([888,999])#同時添加多個
list.remove(999)#刪除指定元素
list.pop()#隨機刪除一個
list.discard(888) # 刪除指定元素,若不存在,報錯
密碼強弱校驗--小例子
import string
all_nums = set(string.digits)#數字
lower = set(string.ascii_lowercase)#所有小寫字母
upper = set(string.ascii_uppercase)#所有大寫字母
punctuation = set(string.punctuation)#所有特殊符號
for i in range(5):
pwd = input(‘請輸入你的密碼:‘).strip()
pwd = set(pwd)
#判斷密碼是否包含大小寫字母和特殊符號
if pwd & all_nums and pwd & lower and pwd & upper and pwd & punctuation:
print(‘密碼合法‘)
else:
print(‘密碼不合法!‘)
三,函數
函數定義規則:
- 函數代碼塊以 def 關鍵詞開頭,後接函數標識符名稱和圓括號 ()。
- 任何傳入參數和自變量必須放在圓括號中間,圓括號之間可以用於定義參數。
- 函數的第一行語句可以選擇性地使用文檔字符串—用於存放函數說明。
- 函數內容以冒號起始,並且縮進。
- return [表達式] 結束函數,選擇性地返回一個值給調用方。不帶表達式的return相當於返回 None。
函數定義實例
def say(name,sex=‘男‘): #函數,形參,形式參數,變量
#必填參數 位置
#默認值參數 非必填
print(‘%s 哈哈哈 性別%s‘%(name,sex) )
#函數體
局部變量與全局變量:在函數裏面的變量全都是局部變量,它只能在函數裏面使用,函數執行結束那麽沒有這個變量
return:如果需要用到函數的處理結果的話,那麽就寫return,不需要的話,那就不用寫,函數裏面如果碰到return,函數立即結束
校驗輸入字符串為小數的程序--小例子
- 只有一個小數點 判斷小數點個數
- 正小數的情況下,小數點左邊和右邊都是整數的話,才合法 [0 ,12]
- 負小數的情況下 小數點右邊整數,左邊 必須以負號開頭,只有一個負號。
def check_float(s):
s = str(s)
if s.count(‘.‘)==1:
s_list = s.split(‘.‘)
left = s_list[0] #小數點左邊 # ‘-98‘
right = s_list[1]#小數點右邊
#這判斷正小數
if left.isdigit() and right.isdigit():
return True
#判斷負小數
if left.startswith(‘-‘) and left[1:].isdigit() and right.isdigit():
return True
return False
Python自動化四--json模塊使用,集合操作,函數