Content:
- JSON module
- Collection operations
- Function
One, the JSON module
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript.
The JSON module can be used to encode JSON data in Python3, which contains two functions:
- json.dump (): encodes the data.
- json.load (): decodes the data.
JSON format Storage--small example
import jsonstu_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-encoded strings are converted back to a Python data structure
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‘])
Working with JSON-formatted files
# 读取数据,以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 store user password registration file--small example
import jsonf = 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()
Two, set operation
A collection (set) is a sequence of unordered, non-repeating elements.
The basic function is to test the membership and remove duplicate elements.
You can create a collection using the curly braces {} or the set () function, note: Creating an empty collection must be set () instead of {}, because {} is used to create an empty dictionary.
To create a format:
= {value01,value02,...}#或者set(value)
To perform a set operation:
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),' intersection ')#交集 Remove Duplicate dataPrint(List. Union (List_2),' and set ')# and set off the weight-unified displayPrint(List. Difference (list_2),' difference set ')#差集-Remove the list with List_2 noList_3= Set([1,3,6])Print(List_3.issubset (List))#子集 The value of list_3 in list allPrint(List. Issuperset (List_3))#父集Print(List. Symmetric_difference (List_2))# Symmetric difference sets Lsit and list_3 don't have each other.A=Set(a) b=Set(b)Print(A-b# A and b difference setsPrint(A|b# A and B are setPrint(A&b# Intersection of a and BPrint(A^b# elements that do not exist simultaneously in A and B
Collection operations:
list=set(list)list.add(777#一次添加一个list.update([888,999])#同时添加多个list.remove(999)#删除指定元素list.pop()#随机删除一个list.discard(888# 删除指定元素,若不存在,报错
Password strength Check-small example
ImportStringall_nums= Set(string.digits)#数字Lower= Set(string.ascii_lowercase)#所有小写字母Upper= Set(string.ascii_uppercase)#所有大写字母Punctuation= Set(string.punctuation)#所有特殊符号 forIinch Range(5): pwd= input(' Please enter your password: '). Strip () pwd= Set(PWD)#判断密码是否包含大小写字母和特殊符号 ifPwd&All_nums andPwd&Lower andPwd&Upper andPwd&Punctuation:Print(' Password legal ')Else:Print(' The password is illegal! ')
Three, function
function definition Rules:
- The function code block begins with a def keyword followed by the function identifier name and parentheses ().
- Any incoming parameters and arguments must be placed in the middle of the parentheses, and the parentheses can be used to define the parameters.
- The first line of the function statement can optionally use the document string-for storing the function description.
- The function contents begin with a colon and are indented.
- return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
function definition Instance
def say(name,sex=‘男‘): #函数,形参,形式参数,变量 #必填参数 位置 #默认值参数 非必填 print(‘%s 哈哈哈 性别%s‘%(name,sex) ) #函数体
local variables and global variables : the variables inside the function are all local variables, it can only be used inside the function, and the function execution ends so there is no such variable
return: If you need to use the result of the function, then write the return, no need, then do not write, function inside if the return, function immediately end
Verify that the input string is a decimal program--small example
- Only one decimal point determines the number of decimal points
- In the case of positive decimals, the left and right of the decimal point are integers, only legal [0, 12]
- In case of negative decimals, the right integer of the decimal point must start with a minus sign and only a minus sign.
defCheck_float (s): s= Str(s)ifS.count ('. ')==1: s_list=S.split ('. ') left=s_list[0]#小数点左边 # ' -98 'Right=s_list[1]#小数点右边 #这判断正小数 ifLeft.isdigit () andRight.isdigit ():return True #判断负小数 ifLeft.startswith ('-') andleft[1:].isdigit () andRight.isdigit ():return True return False
Python automation four--json module use, set operation, function