json操作:
#json就是一个字符串 d = { "error_code": 0, "stu_info": [ { "id": 314, "name": "矿泉水", "sex": "男", "age": 18, "addr": "北京市昌平区", "grade": "摩羯座", "phone": "18317155663", "gold": 100 }, { "id": 315, "name": "矿泉水", "sex": "女", "age": 27, "addr": "上海", "grade": "摩羯座", "phone": "18317155664", "gold": 100 } ] } import json with open('abc.txt','w',encoding= 'utf-8') as fw: json.dump(d,fw,indent=4,ensure_ascii=False) s = json.dumps(d,ensure_ascii=False,indent=4) #把字典转成json,字符串 fw.write(s) #ensure_ascii = False去中文 #indent=4美化文件 with open('abc.txt',encoding= 'utf-8') as fr: result = fr.read() print('result,刚从文件读出来',type(result)) dic = json.loads(result) print('dic,转换完了之后的',dic,type(dic)) #json转换成字典 result = json.load(fr) print('result',type(result))
集合:
#集合天生可以去重set l = [1,2,3,4,1,2,3,] print(set(l))#集合是无序的 s2 = {1, 2, 3, 4} s = set()#空集合 s.add(1)#添加元素 s.remove(1)#删除元素 #交集,并集,差集,对称差集 xn = ['1','2','3'] zdh = ['2','3','4'] xn_set = set(xn) zdh_set = set(zdh) print((xn_set.intersection(zdh_set))) # 取交集 print(xn_set & zdh_set)#取交集 #并集,把两个几个加一起去重 print(xn_set.union(zdh_set)) print(xn_set |zdh_set) #差集,在a里面有的,在b里面没有的 print(xn_set.difference(zdh_set)) print(xn_set - zdh_set) #对称差集,把两个集合里面都有的删掉 print(xn_set.symmetric_difference(zdh_set)) print(xn_set ^ zdh_set)
切片:
l = ['xiaoming', 'xiaohei', 'xiaobai', 'jaojun','小黑'] print(l[1:2])# 顾头不顾尾 print(l[0:6:3])# 2是隔一个取一个,负数是从右往左 #非空即真,非0即真 #列表生成式 for i in range(1,100): if i%2 == 0: l.append(i) print(l) result = [str(i).zfill(2) for i in range(1,10)if i <10]#简化写作,后面可以加if条件 print(result) result2 = []#同上一个意思 for i in range(1,10): j= str(i).zfill(2) result2.append(j) print(result2) result = [i+1 for i in range(1,10)] result2=[] for i in range(1,10): result2.append(i+1) print(result) #三元表达式 id_card = '410881199211111111' if id_card [-2]%2 == 0 sex = 'nv' else: sex = 'nan' sex = '女' if int(id_card[-2] )%2 == 0 else '男'#三元表达式 print(sex) li = [1,1,2,3,4,5,6,7,8,9] li2 = [1,1,2,3,4,5,6,7,8,9] import copy #li2 = li[:] #深拷贝 #li2 = li #浅拷贝 #li3 = copy.deepcopy(li)深拷贝 for i in li2: if i%2!=0: li.remove(i) print(li) #循环的时候不要删list里面的元素,会导致下标错乱 #两个list 可以避免此问题 #浅拷贝,深拷贝